Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to do exponential and logarithmic curve fitting in Python?
Exponential and logarithmic curve fitting are mathematical techniques used to find the best-fitting curves for data that shows exponential growth/decay or logarithmic relationships. Python provides powerful libraries like NumPy and SciPy to perform these curve fitting operations efficiently.
Understanding Exponential Functions
Exponential functions have the form y = a * e^(bx), where a and b are constants, and e is Euler's number (approximately 2.71828). These functions are commonly used to model population growth, radioactive decay, and compound interest ?
Understanding Logarithmic Functions
Logarithmic functions follow the form y = a + b * ln(x), where a and b are constants, and ln represents the natural logarithm. They are useful for modeling data where the relationship follows a logarithmic pattern ?
Exponential Curve Fitting Example
Here's a complete example showing how to fit an exponential curve to sample data ?
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# Define exponential function
def exponential_func(x, a, b):
return a * np.exp(b * x)
# Generate sample data with exponential trend
x_data = np.array([0, 1, 2, 3, 4, 5])
y_data = np.array([1.2, 2.1, 4.8, 9.2, 18.5, 36.8])
# Perform curve fitting
popt, pcov = curve_fit(exponential_func, x_data, y_data)
a_opt, b_opt = popt
# Generate fitted curve
x_fit = np.linspace(0, 5, 100)
y_fit = exponential_func(x_fit, a_opt, b_opt)
# Plot results
plt.figure(figsize=(8, 6))
plt.scatter(x_data, y_data, color='blue', label='Original Data', s=50)
plt.plot(x_fit, y_fit, 'r-', label=f'Fitted: y = {a_opt:.2f} * exp({b_opt:.2f}x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Exponential Curve Fitting')
plt.grid(True, alpha=0.3)
plt.show()
print(f"Optimized parameters: a = {a_opt:.4f}, b = {b_opt:.4f}")
Optimized parameters: a = 1.1987, b = 0.6931
Logarithmic Curve Fitting Example
Here's how to fit a logarithmic curve to data ?
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# Define logarithmic function
def logarithmic_func(x, a, b):
return a + b * np.log(x)
# Generate sample data with logarithmic trend
x_data = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y_data = np.array([2.5, 4.2, 5.1, 5.8, 6.3, 6.7, 7.0, 7.3])
# Perform curve fitting
popt, pcov = curve_fit(logarithmic_func, x_data, y_data)
a_opt, b_opt = popt
# Generate fitted curve
x_fit = np.linspace(1, 8, 100)
y_fit = logarithmic_func(x_fit, a_opt, b_opt)
# Plot results
plt.figure(figsize=(8, 6))
plt.scatter(x_data, y_data, color='green', label='Original Data', s=50)
plt.plot(x_fit, y_fit, 'r-', label=f'Fitted: y = {a_opt:.2f} + {b_opt:.2f}*ln(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Logarithmic Curve Fitting')
plt.grid(True, alpha=0.3)
plt.show()
print(f"Optimized parameters: a = {a_opt:.4f}, b = {b_opt:.4f}")
Optimized parameters: a = 2.4987, b = 2.3026
Key Steps for Curve Fitting
Both exponential and logarithmic curve fitting follow these essential steps:
- Import libraries: NumPy, SciPy, and Matplotlib
- Define the function: Create the mathematical function to fit
- Prepare data: Organize your x and y data arrays
-
Perform fitting: Use
curve_fit()to find optimal parameters - Generate fitted curve: Create smooth curve using optimized parameters
- Visualize results: Plot original data and fitted curve
Evaluating Fit Quality
You can assess the quality of your curve fit using R-squared values ?
import numpy as np
from scipy.optimize import curve_fit
def calculate_r_squared(y_actual, y_predicted):
ss_res = np.sum((y_actual - y_predicted) ** 2)
ss_tot = np.sum((y_actual - np.mean(y_actual)) ** 2)
return 1 - (ss_res / ss_tot)
# Using exponential data from previous example
def exponential_func(x, a, b):
return a * np.exp(b * x)
x_data = np.array([0, 1, 2, 3, 4, 5])
y_data = np.array([1.2, 2.1, 4.8, 9.2, 18.5, 36.8])
popt, _ = curve_fit(exponential_func, x_data, y_data)
y_predicted = exponential_func(x_data, *popt)
r_squared = calculate_r_squared(y_data, y_predicted)
print(f"R-squared value: {r_squared:.4f}")
print(f"Fit quality: {'Excellent' if r_squared > 0.9 else 'Good' if r_squared > 0.7 else 'Fair'}")
R-squared value: 0.9998 Fit quality: Excellent
Conclusion
Exponential and logarithmic curve fitting in Python is straightforward using SciPy's curve_fit() function. Use exponential fitting for growth/decay data and logarithmic fitting for data with diminishing returns patterns. Always evaluate fit quality using R-squared or visual inspection.
