python-scipyHow do I use Python and SciPy to fit an exponential curve?
To use Python and SciPy to fit an exponential curve, you can use the curve_fit function from scipy.optimize. This function takes a user-defined function that models the data as well as the x and y data points as arguments. It then returns an array of optimized parameters that best fit the data.
Example code
import numpy as np
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
xdata = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
ydata = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
popt, pcov = curve_fit(func, xdata, ydata)
print(popt)
Output example
[ 1.5 -1. ]
Code explanation
import numpy as np: imports thenumpylibrary asnp, which is used to define the x and y data points.from scipy.optimize import curve_fit: imports thecurve_fitfunction from thescipy.optimizelibrary, which is used to fit the data points to an exponential curve.def func(x, a, b):: defines a user-defined function that takes x and two parameters (a and b) as arguments and returns an exponential function.xdata = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]): defines the x data points as a numpy array.ydata = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]): defines the y data points as a numpy array.popt, pcov = curve_fit(func, xdata, ydata): uses thecurve_fitfunction to fit the data points to the user-defined exponential function. It returns an array of optimized parameters that best fit the data.print(popt): prints the optimized parameters.
Helpful links
More of Python Scipy
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a zero matrix using Python and Numpy?
- How do I use the scipy ttest_ind function in Python?
- How can I use Python and SciPy to generate a Voronoi diagram?
- How do I calculate variance using Python and SciPy?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How to use Python, XML-RPC, and NumPy together?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...