更改根查找中的系数值

Changing coefficient values in root finding

我有以下代码:

import numpy as np
import scipy as sc
from scipy import optimize


def fun(cd, pd, cr,  p1, lambda1,prev,n2, inspIdx):
    n1 = prev + n2
    deltan1 = cd*pd*lambda1*(1-p1)*n1 - cr*(1-pd)*(1-p1)*lambda1*n1*np.exp(-lambda1*pd*n1)
    deltan2 = cd*pd*lambda1*(1-p1)*n2 - cr*(1-pd)*(1-p1)*lambda1*n2*np.exp(-lambda1*pd*n2)
    return p1**inspIdx * deltan1 + (1-p1**inspIdx) * deltan2

n2 是我要求这个非线性函数根的变量。但是,其他变量的值在每次迭代时都会发生变化,并且它们在主函数的 for 循环中。

我检查了 SymPy,但不知道如何更改系数值。如何分配系数值并找到关于 n2 的根?

如果我没理解错的话,你可以这样做:

import numpy as np
from scipy.optimize import root

# given values for the other variables
cd = pd = cr = p1 = lambda1 = prev = inspIdx = 0.5

# find the root of the function n2 -> fun(...,n2,..)
# res.x contains the root
res = root(lambda n2: fun(cd, pd, cr, p1, lambda1, prev, n2, inspIdx), x0 = [0.0])