gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:02:48 30 4
gpt4 key购买 nike

我想以某种方式缩短我的 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.| (default, Oct 15 2017, 07:29:16) [MSC v.1900 32 bit (Intel)] Type "copyright", "credits" or "license" for more information.

IPython 6.1.0 -- An enhanced Interactive Python.

runfile('C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py', wdir='C:/Users/Matteo S/Desktop/vocaboli tedesco') Traceback (most recent call last):

File "C:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns)

File "", line 1, in runfile('C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py', wdir='C:/Users/Matteo S/Desktop/vocaboli tedesco')

File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace)

File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Matteo S/Desktop/vocaboli tedesco/untitled0.py", line 17 def fe(P[0]): ^ SyntaxError: invalid syntax

最佳答案

函数不应该知道您正在传递可迭代的第一个元素,他应该只知道您正在传递一个数字。另一方面,在这种情况下,函数 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()

关于python - 如何使用辅助函数缩短 ODE 方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335671/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com