The question is from this link for using python to fit a curve
https://riptutorial.com/scipy/example/31081/fitting-a-function-to-data-from-a-histogram
# 5.) Fit the function to the histogram data.
popt, pcov = curve_fit(fit_function, xdata=binscenters, ydata=data_entries, p0=[20000, 2.0, 2000, 3.0, 0.3])
print(popt)
# 6.)
# Generate enough x values to make the curves look smooth.
xspace = np.linspace(0, 6, 100000)
# Plot the histogram and the fitted function.
plt.bar(binscenters, data_entries, width=bins[1] - bins[0], color='navy', label=r'Histogram entries')
plt.plot(xspace, fit_function(xspace, *popt), color='darkorange', linewidth=2.5, label=r'Fitted function'
popt is a numpy array, *popt seems not about multiplication. What could it be?
I printed popt
and *popt
, I got
[ 2.01844780e 03 8.72591456e 03 3.00208158e 00 -2.81683457e 01]
2018.447795213082 8725.914563215998 3.002081584102449 -28.16834574461017
still not sure what is the role of star and how it works in plot (seems has to be there)
CodePudding user response:
According the curve_fit
docs, the function has to have form
f(x, …)
which it will call with f(xdata, *p0)
. p0
is the tuple of fitting parameters, initially [20000, 2.0, 2000, 3.0, 0.3]
, and at the end the popt
list (or tuple).
Used in the plot function
fit_function(xspace, *popt)
it does the same thing.
fit_function(xdata, 20000, 2.0, ....)
Python calls this unpacking
.
Looks like popt
is an array:
In [152]: np.array([ 2.01844780e 03, 8.72591456e 03, 3.00208158e 00, -2.81683457e 01])
Out[152]: array([ 2.01844780e 03, 8.72591456e 03, 3.00208158e 00, -2.81683457e 01])
In [153]: print(np.array([ 2.01844780e 03, 8.72591456e 03, 3.00208158e 00, -2.81683457e 01]))
[ 2.01844780e 03 8.72591456e 03 3.00208158e 00 -2.81683457e 01]
the unpacked version:
In [154]: print(*np.array([ 2.01844780e 03, 8.72591456e 03, 3.00208158e 00, -2.81683457e 01]))
2018.4478 8725.91456 3.00208158 -28.1683457
A simpler example of this unpacking in the print function:
In [155]: print([1,2])
[1, 2]
In [156]: print(1,2)
1 2
In [157]: print(*[1,2])
1 2