如何使用辅助函数缩短ODE方程

问题描述 投票:1回答:1

我想以某种方式缩短我的ODE方程,因为否则代码会变得凌乱。我尝试过使用辅助函数,比如fe(),但这不起作用。下面的代码只是一个例子欢迎任何建议!谢谢!

# Import the required modules
import numpy as np
import matplotlib.pyplot as plt

from scipy.integrate import odeint

# Here the parameters
a,b,c,d = 1,1,1,1

def fe(P[0]):
    return d*P[0]

# Define a function which calculates the derivative
def dP_dl(P, l):
    return [P[0]*(a - b*P[1]),
            -P[1]*(c - fe(P[0]) )]


ts = np.linspace(0, 12, 100)
P0 = [1.5, 1.0]
Ps = odeint(dP_dl, P0, ts) 
prey = Ps[:,0]
predators = Ps[:,1]


plt.plot(ts, prey, "+", label="Rabbits")
plt.plot(ts, predators, "x", label="Foxes")
plt.xlabel("Time")
plt.ylabel("Population")
plt.legend();

这是我从python控制台得到的。

Python 3.6.3 | Anaconda,Inc。| (默认,2017年10月15日,07:29:16)[MSC v.1900 32 bit(Intel)]输入“copyright”,“credits”或“license”以获取更多信息。

IPython 6.1.0 - 增强的交互式Python。

runfile('C:/ Users / Matteo S / Desktop / vocaboli tedesco / untitled0.py',wdir ='C:/ Users / Matteo S / Desktop / vocaboli tedesco')Traceback(最近一次调用最后一次):

在run_code exec中的文件“C:\ Anaconda3 \ lib \ site-packages \ IPython \ core \ interactiveshell.py”,第2862行(code_obj,self.user_global_ns,self.user_ns)

文件“”,第1行,在runfile中('C:/ Users / Matthew S / Desktop / German words / untitled0.py',wdir ='C:/ Users / Matthew S / Desktop / German words')

文件“C:\ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,第710行,在runfile execfile(filename,namespace)中

文件“C:\ Anaconda3 \ lib \ site-packages \ spyder \ utils \ site \ sitecustomize.py”,第101行,execfile exec(compile(f.read(),filename,'e​​xec'),namespace)

文件“C:/ Users / Matteo S / Desktop / vocaboli tedesco / untitled0.py”,第17行def fe(P [0]):^ SyntaxError:语法无效

python ode odeint
1个回答
1
投票

函数不应该知道你传递的是iterable的第一个元素,他应该只知道你传递了一个数字。另一方面,在函数dP_dl被设置为分离组件以使其更具可读性的情况下。

# Import the required modules
import numpy as np
import matplotlib.pyplot as plt

from scipy.integrate import odeint

# Here the parameters
a,b,c,d = 1,1,1,1

def fe(x): return d*x

# Define a function which calculates the derivative
def dP_dl(P, l):
    x1, x2 = P
    dx1dt = x1*(a-b*x2)
    dx2dt = -x2*(c-fe(x1)) 
    return dx1dt, dx2dt


ts = np.linspace(0, 12, 100)
P0 = [1.5, 1.0]
Ps = odeint(dP_dl, P0, ts) 
prey = Ps[:,0]
predators = Ps[:,1]


plt.plot(ts, prey, "+", label="Rabbits")
plt.plot(ts, predators, "x", label="Foxes")
plt.xlabel("Time")
plt.ylabel("Population")
plt.legend();
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.