简体   繁体   中英

Polynomial fit using curve_fit()

I've been attempting to get the best polynomial fit possible for my data points using curve_fit() yet my code is giving the following error. Could somebody assist me comprehend where the glitch lies. Many thanks in advance.

TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

from scipy.optimize import curve_fit
from scipy.interpolate import *   
def func(x, a, b, c, d):
    return a*x^3 + b*x^2 + c * x + d

Xdata1 = np.array([10, 20, 30, 60])
Ydata1 = np.array([3, 5, 4, 3.5])

plt.plot(Xdata1, Ydata1, 'bo', label='Raw Data')

popt, pcov = curve_fit(func, Xdata1, Ydata1)
a, b, c, d= popt
plt.plot(Xdata1, func(Xdata1, *popt), 'r--', label='fit')

您应该使用**而不是^ ,这是按位运算符

As pointed out already ^ is a bit-wise operator, namely the bitwise XOR (exclusive OR) operator.

https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations

In any case since you are trying to fit a regular polynomial, if you don't want to deal with custom functions and arguments specification in the scipy.optimize package, you can also try the numpy.polyfit fucntion. You can specify the polynomial degree and get the coefficient right away. It uses a least square approach.

In your case would be something like

numpy.polyfit(Xdata1,Ydata1,3)

which yields the coefficients of the degreee 3 fitting polynomial

array([ 0.34166667, -3.55 , 10.25833333, -4.05 ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM