Function
Fit a function using nonlinear least squares
Features
Official document
input
parameter | Value |
---|---|
f | function, it must take xdata as the first input parameter |
xdata | Measured Independent Data |
ydata | The associated data, nominally the result of f(xdata,…) |
output
output | Value |
---|---|
popt | The optimal value, that is, the value output by the fitting function according to x |
pcov | covariance matrix of popt |
infodict | a dictionary of optional outputs with the keys (returned only if full_output is True) |
message | Related information (returned only if full_output is True) |
ier | An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable mesg gives more information. (returned only if full_output is True) |
example
official example
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def official_demo_func(x, a, b, c):
return a * np.exp(-b * x) + c
def official_demo():
x = np.linspace(0, 4, 50)
y = official_demo_func(x, 2.5, 1.3, 0.5)
rng = np.random.default_rng()
y_noise = 0.2 * rng.normal(size=x.size)
ydata = y + y_noise
plt.plot(x, ydata, 'b-', label='data')
popt, pcov = curve_fit(official_demo_func, x, ydata)
print(popt)
plt.plot(x, official_demo_func(x, *popt), 'g--',
label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
official_demo()
The output fitting result is
[2.61499295 1.35033395 0.51541771]
It is still very close to the input value [2.5, 1.3, 0.5].