对具有额外参数的函数使用scipysolve_ivp [英] using scipy solve_ivp for a function with extra arguments
问题描述
我正在尝试使用solve_ivp解决初始值问题。问题是我的函数f(x,y)= dy / dx包含额外的参数。我尝试使用此功能:
I am trying to solve an initial value problem with solve_ivp. The problem is that my function f(x,y)=dy/dx contain extra arguments. I tried to use this:
为resolve_ivp(新的SciPy ODE API)传递参数
,但它总是给我错误。这是代码:
but it keeps giving me errors. Here is the code:
from numpy import arange
import math
import numpy as np
from scipy.integrate import solve_ivp
from numpy import pi
sigmav = 1.0e-9
Mpl = 1.22e19
ms=100.0
gg=100.0
gs=106.75
def Yeq(x):
return 0.145*(gg/gs)*(x)**(3/2)*np.exp(-x)
def ss(x,m_dm):
return (2/45)*((pi)**2)*gs*(m_dm**3/x**3)
def hubb(x,m_dm):
return 1.66*(gg**(1/2))*(m_dm**2/Mpl)*(1/x**2)
def derivada(x,yl,m_dm,σv):
return -(σv*ss(x,m_dm)*((yl**2)-(Yeq(x)**2)))/(x*hubb(x,m_dm))
xx=np.logspace(np.log10(3),3,100)
y00 = Yeq(xx[0])
x00 = xx[0]
sigmav = 1.7475e-9
ms=100.0
solucion1 = solve_ivp(fun=lambda x, y: derivada(x, y, args=(ms,sigmav),[np.min(xx),np.max(xx)],[y00],method='BDF',rtol=1e-10,atol=1e-10))
当我尝试为solucion1运行单元时,它将返回以下:
When I try to run the cell for solucion1, it returns the following:
File "<ipython-input-17-afcf6c3782a9>", line 6
solucion1 = solve_ivp(fun=lambda x, y: derivada(x, y, args=(ms,sigmav),[np.min(xx),np.max(xx)],[y00],method='BDF',rtol=1e-10,atol=1e-10))
^
SyntaxError: positional argument follows keyword argument
一定很容易,但是我刚刚开始使用python,所以请帮我。
It must be something very easy but I am just starting to work with python, so please help me with this.
推荐答案
您只需将右括号放在错误的位置。由于 derivada
没有命名的args,因此删除那里的args语句,lambda表达式已经绑定了这些附加参数。另外,传递的函数也不是命名参数
You simply mis-placed a closing parenthesis. As derivada
has no named args, remove the args statement there, the lambda expression already binds these additional parameters. Also, the passed function is not a named argument
solucion1 = solve_ivp(lambda x, y: derivada(x, y, ms, sigmav),[np.min(xx),np.max(xx)], [y00], method='BDF', rtol=1e-10, atol=1e-10)
或您在github讨论中引用的形式,其中参数列表在其他位置构造
or in the form that you cite from the github discussion, where the parameter list is constructed elsewhere
args = ( ms, sigmav )
solucion1 = solve_ivp(lambda x, y: derivada(x, y, *args),[np.min(xx),np.max(xx)], [y00], method='BDF', rtol=1e-10, atol=1e-10)
这篇关于对具有额外参数的函数使用scipysolve_ivp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!