Skip to main content
 首页 » 编程设计

python之在 Python 中查找函数的根

2025年05月04日8EasonJim

我正在尝试使用 scipy 函数 fsolve 计算函数的根,但错误不断标记:

TypeError: 'numpy.array' object is not callable 

我认为将方程式定义为函数可能更容易,但我已经尝试了几次都无济于事。

代码:

import scipy 
import numpy as np 
import matplotlib.pyplot as plt 
from scipy import optimize 
 
# Constants 
wavelength = 0.6328 
ncore = 1.462420 
nclad = 1.457420 
a = 8.335 
 
# Mode Order 
l = 0 
 
# Mode parameters 
V = (2 * np.pi * a / wavelength) * np.sqrt(ncore**2 - nclad**2) 
U = np.arange(0, V, 0.01) 
W = np.sqrt(V**2-U**2) 
 
func = U * scipy.special.jv(l+1, U) / scipy.special.jv(l, U) - W * scipy.special.kv(l+1, W) / scipy.special.kv(l, W) 
 
from scipy.optimize import fsolve 
x = fsolve(func,0) 
print x 

堆栈跟踪:

Traceback (most recent call last): 
 
  File "<ipython-input-52-081a9cc9c0ea>", line 1, in <module> 
    runfile('/home/luke/Documents/PythonPrograms/ModeSolver_StepIndex/ModeSolver_StepIndex.py', wdir='/home/luke/Documents/PythonPrograms/ModeSolver_StepIndex') 
 
  File "/usr/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 580, in runfile 
    execfile(filename, namespace) 
 
  File "/home/luke/Documents/PythonPrograms/ModeSolver_StepIndex/ModeSolver_StepIndex.py", line 52, in <module> 
    x = fsolve(func,0) 
 
  File "/usr/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 140, in fsolve 
    res = _root_hybr(func, x0, args, jac=fprime, **options) 
 
  File "/usr/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 197, in _root_hybr 
    shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,)) 
 
  File "/usr/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 20, in _check_func 
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) 
 
TypeError: 'numpy.ndarray' object is not callable 

请您参考如下方法:

那是因为 fsolve 接受一个函数作为参数。 试试这个,注意你仍然会遇到一些运行时错误,你将不得不检查你从 func 返回的构造是否正确,我会把它留给你弄清楚。

import scipy 
import numpy as np 
import matplotlib.pyplot as plt 
from scipy import optimize 
 
# Constants 
wavelength = 0.6328 
ncore = 1.462420 
nclad = 1.457420 
a = 8.335 
 
# Mode Order 
# l = 0 
 
# Mode parameters 
V = (2 * np.pi * a / wavelength) * np.sqrt(ncore**2 - nclad**2) 
U = np.arange(0, V, 0.01) 
W = np.sqrt(V**2-U**2) 
 
def func(l): 
    return U * scipy.special.jv(l+1, U) / scipy.special.jv(l, U) - W * scipy.special.kv(l+1, W) / scipy.special.kv(l, W) 
 
from scipy.optimize import fsolve 
x = fsolve(func,0) 
print x