# Definition de la fonction affine
def f_aff(x, a, b):
return a*x+b
# Montecarlo
def montecarlo(X, Y, uX, uY, N_mc=100, color1='r', color2='b', mini=None, maxi=None):
sigma_X = uX*np.ones(X.size)
sigma_Y = uY*np.ones(Y.size)
param = np.zeros((2,N_mc))
for i in range(N_mc):
x_mc = npr.normal(loc=X, scale=sigma_X)
y_mc = npr.normal(loc=Y, scale=sigma_Y)
pop, pcov = curve_fit(f_aff, x_mc, y_mc)
param[0,i] = pop[0]
param[1,i] = pop[1]
mini = mini if mini else X.min()
maxi = maxi if maxi else X.max()
x_th = np.linspace(mini, maxi, 4)
y_th = f_aff(x_th, *pop)
for i in range(N_mc):
y_th = f_aff(x_th, *param[:,i])
#plt.plot(x_th, y_th, color2, alpha=0.05) #ligne à décommenter si on veut afficher les 100 droites
plt.errorbar(X, Y, xerr=uX, yerr=uY, fmt='+', capsize=2, color=color1,label="Mesures")
# plt.show()
a_moy = np.mean(param[0,:])
b_moy = np.mean(param[1,:])
x = np.linspace(0.8*min(X),max(X)*1.1,100)
plt.plot(x,f_aff(x,a_moy,b_moy),'b--',label='Ajustement')
#print("La pente moyenne sur les ", N_mc, "mesures est de :", np.round(a_moy,4))
a_sig = np.std(param[0,:]) #ecart type
b_sig = np.std(param[1,:]) #ecart type
#print("L'écart type entre les pentes des", N_mc, "mesures est de :", np.round(a_sig,4))
#print("Le résultat est donc de :", f"a = {a_moy:.3f} +/- {a_sig:.3f}")
#print("Cela correspond à une erreur de:", f"a_rel = {a_sig/a_moy*100:.0f} %")
return (a_moy, a_sig, b_moy, b_sig)