1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #! python3
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
""" Choix de l'équation ?
Voir : https://www.md.ucl.ac.be/tutorial/tutorial/didacphys/rappels/math/fonctions/expon.html
"""
return a * (1.0 - np.exp(-b * x))
""" Générer les données x, y """
x = np.linspace(0, 3, 100)
y = func(x, 3, 2)
plt.plot(x, y, color="yellow", label="func(x,3,2)")
""" Ajouter du bruit (Gaussian distribution)
pour simuler les données expérimentales.
"""
noise = 0.2 * np.random.normal(size=y.size)
y_noise = y + noise
plt.scatter(x, y_noise, s=5, c="red", label="y_noise")
""" Curve Fit """
init_vals = [1, 1] # for [a, b]
best_vals, covar = curve_fit(func, x, y_noise, p0=init_vals)
print('best_vals: {}'.format(best_vals)) # best_vals: [2.96412058 2.05106931]
y_fit = func(x, best_vals[0], best_vals[1])
plt.plot(x, y_fit, label="y_fit") # très proche de la courbe func(x, 3, 2)
plt.legend()
plt.show() |
Partager