write a simple code that generates 10 random (y,x) data that are around a simple eponential and a least square fit of these data with aa y=a*exp(b*x)+c target function. in python

main.py
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# Generate random data around an exponential function
np.random.seed(0)
x_data = np.random.uniform(0, 5, 10)
y_data = 2 * np.exp(0.5 * x_data) + 1 + np.random.normal(0, 0.5, 10)

# Define the target function
def func(x, a, b, c):
    return a * np.exp(b * x) + c

# Perform a least squares fit
popt, pcov = curve_fit(func, x_data, y_data)

# Print the fitted parameters
print('Fitted parameters: a = %.2f, b = %.2f, c = %.2f' % tuple(popt))

# Generate x values for plotting the fitted function
x_fit = np.linspace(0, 5, 100)

# Generate the fitted function values
y_fit = func(x_fit, *popt)

# Plot the data and the fitted function
plt.plot(x_data, y_data, 'ko', label='Data')
plt.plot(x_fit, y_fit, 'r-', label='Fit')
plt.legend()
plt.show()
833 chars
31 lines

This code first generates random data points around an exponential function, then uses the curve_fit function from scipy.optimize to perform a least squares fit of the data to the target function. The fitted parameters are then printed and used to generate the fitted function values for plotting. Finally, the data points and the fitted function are plotted using matplotlib.

related categories

gistlibby LogSnag