"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you perform exponential and logarithmic curve fitting in Python beyond polynomial fitting?

How do you perform exponential and logarithmic curve fitting in Python beyond polynomial fitting?

Published on 2024-11-20
Browse:352

How do you perform exponential and logarithmic curve fitting in Python beyond polynomial fitting?

Exponential and Logarithmic Curve Fitting in Python Beyond Polynomial Fitting

In addition to polynomial fitting, which has the polyfit() function in Python, there exist techniques for fitting exponential and logarithmic curves.

Logarithmic Curve Fitting

To fit a curve to the model y = A B log x, we can transform the data by taking the logarithm of both sides, resulting in log y = log A B log x. By fitting log y against log x using polyfit(), we obtain the coefficients log A and B.

import numpy as np

x = np.array([1, 7, 20, 50, 79])
y = np.array([10, 19, 30, 35, 51])
coeffs = np.polyfit(np.log(x), y, 1)

print("Coefficients:", coeffs)
print("y ≈", coeffs[1], " ", coeffs[0], "log(x)")

Exponential Curve Fitting

To fit a curve to the model y = Ae^(Bx), we can take the logarithm of both sides, resulting in log y = log A B x. The parameters can then be determined by fitting log y against x using polyfit().

x = np.array([10, 19, 30, 35, 51])
y = np.array([1, 7, 20, 50, 79])
coeffs = np.polyfit(x, np.log(y), 1)

print("Coefficients:", coeffs)
print("y ≈", np.exp(coeffs[1]), "*", "exp(", coeffs[0], "x)")

Note on Bias in Unweighted Fitting

It's worth noting that unweighted fitting (without considering the weights of the data points) can lead to bias towards small values, particularly in exponential curve fitting. To mitigate this, weights can be included in the fitting process, proportional to the y-values.

Using Scipy for Curve Fitting

Scipy provides the curve_fit() function to perform nonlinear curve fitting. This allows us to fit any model directly, without transformations.

from scipy.optimize import curve_fit

# Logarithmic curve fitting
popt, pcov = curve_fit(lambda t, a, b: a   b * np.log(t), x, y)
print("Coefficients:", popt)
print("y ≈", popt[1], " ", popt[0], "log(x)")

# Exponential curve fitting
popt, pcov = curve_fit(lambda t, a, b: a * np.exp(b * t), x, y, p0=(1, 0.1))
print("Coefficients:", popt)
print("y ≈", popt[0], "*", "exp(", popt[1], "x)")
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3