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 thenumpy
library asnp
, which is used to define the x and y data points.from scipy.optimize import curve_fit
: imports thecurve_fit
function from thescipy.optimize
library, 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_fit
function 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 do I create a 2D array of zeros using Python and NumPy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python Scipy to zoom in on an image?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and Numpy to parse XML data?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python and SciPy to generate a Voronoi diagram?
- How do I use Python and SciPy to perform linear regression?
- How can I use Python and SciPy to read and write WAV files?
See more codes...