Responsive Navbar with Google Search
☰ Menu
Home
Python
LaTeX
GNUPlot
Arduino
Feedback
Contact Us
Curve Fitting: Using Scipy.optimize
Curve Fitting
Using Numpy
Using Scipy.optimize
Using Scipy.optimize: Program 1
Data Fitting using scipy.optimize
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt # Data x = np.linspace(0, 10, 32) y = np.array([1.2, 2.3, 3.1, 4.5, 6.0, 7.2, 8.1, 9.5, 11.0, 12.5, 14.0, 15.5, 17.2, 19.0, 21.0, 23.5, 26.0, 29.0, 31.5, 34.0, 37.2, 40.0, 43.5, 47.0, 51.0, 55.5, 60.0, 65.0, 70.5, 76.0, 82.5, 90.0]) def func(x, a, b, c): return a * np.exp(b * x) + c # Perform the curve fitting params, covariance = curve_fit(func, x, y) # Extract the slope (a) and intercept (b) a, b, c = params # Generate fitted y-values y_fitted = func(x, a, b, c) # Plotting the data and the fitted line plt.figure(figsize=(8,6)) plt.plot(x, y, 'bo', label='Data') plt.plot(x, y_fitted, 'r-', label=f'Fit: $y = {a:.2f}e^{{{b:.2f}x}} + ({c:.2f})$') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.title('Data Fitting using Scipy Curve Fit') plt.savefig('fit.png') # Print the parameters print(f"parameter (a): {a:.2f}") print(f"parameter (b): {b:.2f}") print(f"parameter (c): {c:.2f}")
Run Code
Output 1