我正在编写一个python代码来创建一个圆的曲线拟合,并将其与原始数据一起绘制。我在这里举了几个例子:https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html但无法理解为什么我的代码中会出现这个错误,说数组不可调用。这是什么意思?注释"之后的最后一块代码;curvefit";是错误发生的地方。错误如下:(这里的数组是calcCircleFunction((的结果(
runfile('/untitled25.py', wdir='C:/XYZsara/testing/testing stj file')
r= 5
[10. 9.53518102 7.69656593 8.85865225 11.77599647 14.26300842
16.59986154 18.86270235 21.08280172 23.27574271 25.45026401 27.6116804
29.76342361 31.90781435 34.04648108 36.18060165 38.31104984 40.43848797
42.56342747 44.68626971]
Traceback (most recent call last):
File "untitled25.py", line 46, in <module>
popt = curve_fit(circle, xTraj,yTraj) #array of curve fit version of circles
File "anaconda3libsite-packagesscipyoptimizeminpack.py", line 686, in curve_fit
args, varargs, varkw, defaults = _getargspec(f)
File "anaconda3libsite-packagesscipy_lib_util.py", line 298, in getargspec_no_self
sig = inspect.signature(func)
File "anaconda3libinspect.py", line 3083, in signature
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
File "anaconda3libinspect.py", line 2833, in from_callable
follow_wrapper_chains=follow_wrapped)
File "anaconda3libinspect.py", line 2208, in _signature_from_callable
raise TypeError('{!r} is not a callable object'.format(obj))
TypeError: array([10. , 9.53518102, 7.69656593, 8.85865225, 11.77599647,
14.26300842, 16.59986154, 18.86270235, 21.08280172, 23.27574271,
25.45026401, 27.6116804 , 29.76342361, 31.90781435, 34.04648108,
36.18060165, 38.31104984, 40.43848797, 42.56342747, 44.68626971]) is not a callable object
from random import random
from scipy.optimize import fsolve, curve_fit
import numpy as np
import matplotlib.pyplot as plt
xi = 0
xf = 40
yi = 0
radius = 5
numPoints = 20
xdata = np.linspace(xi,xf,numPoints)
def calcCircleFunction(x): #calculate the function of circle in 2D
[a,b] = calcCenters(vars)
print("r=",radius)
circle = np.sqrt(abs((x-a)**2-radius**2)) + b
return circle
def calcCenters(vars):
a, b = fsolve(solve_ab, [1,1])
return [a,b]
def solve_ab(vars):
a,b = vars
f1 = (xi-a)**2 + (yi-b)**2 - radius**2
f2 = (xi-a)**2 + ((yi+2*radius)-b)**2 - radius**2
f = [f1,f2]
return f
circle = calcCircleFunction(xdata)
print(circle)
"""curvefit"""
xTraj = np.linspace(xi,xf,numPoints)
yTraj = circle + 0.01*random() #with noise
#print(yTraj)
popt = curve_fit(circle, xTraj,yTraj) #array of curve fit version of circles
plt.plot(xTraj, yTraj, 'b-') #plots the originral trajecory
plt.plot(xdata, calcCircleFunction(xdata, *popt), 'r-')
plt.show()
好吧,curve_fit
的第一个参数需要一个函数,而不是数组或列表。