能否让scipy.integrate.odeint输出内部计算?

2024-05-15 15:08:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把内部计算传递给odeint。我通常在完成积分后重新计算值,但我更喜欢在odeint的调用函数中进行所有计算。在

我的问题在计算上并不繁重,所以在ode解算器内部进行计算时稍微提高一点性能是可以接受的。在

from scipy.integrate import odeint
import numpy as np

def eom(y, t):
    internal_calc = y/(t+1)
    xdot = y

    return xdot, internal_calc

if __name__ == '__main__':

    t = np.linspace(0, 5, 100)
    y0 = 1.0  # the initial condition

    output, internal_calc = odeint(eom, y0, t)

这段代码不运行,但希望能显示我的目标。我想从eom函数中得到每次通过积分器的“内部计算”值。在

我四处寻找选择,但我认识的一位最好的python程序员告诉我要编写自己的集成器,这样我就可以随心所欲了。在

在我这么做之前,我想我应该问问其他人是否有从odeint解算器中获取值的方法。在


Tags: fromimportnpcalcscipy性能算器internal
1条回答
网友
1楼 · 发布于 2024-05-15 15:08:28

有可能,您只是不能使用eom函数的返回值。所以您需要其他方法从eom中走私数据。有很多很多不同的方法可以做到这一点。最简单的方法可能是只使用全局变量:

import scipy.integrate as spi

count = 0

def pend(t, y):
    global count

    theta, omega = y
    dydt = [omega, -.25*omega - 5*np.sin(theta)]

    count += 1
    return dydt

sol = spi.solve_ivp(pend, [0, 10], [np.pi - 0.1, 0.0])
print(count)

输出:

^{pr2}$

另外,请注意,我在上面的代码中使用了solve_ivp,而不是{}。^{} docs表示在编写新代码时,现在应该使用solve_ivp,而不是旧的{}。在

如果这是我自己的代码,我可能会通过将累加器对象传递到函数的部分版本来完成任务:

class Acc:
    def __init__(self):
        self.x = 0

    def __str__(self):
        return str(self.x)

def pend_partial(acc):
    def pend(t, y):
        theta, omega = y
        dydt = [omega, -.25*omega - 5*np.sin(theta)]

        acc.x += 1
        return dydt
    return pend

count = Acc()
sol = spi.solve_ivp(pend_partial(count), [0, 10], [np.pi - 0.1, 0.0])
print(count)

输出:

^{pr2}$

但是,如果您只是编写一个简短的脚本或其他东西,您可能应该使用更简单的global方法。这是一个非常好的用例。在

相关问题 更多 >