import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def GaussFit():
xdata_raw = [0,24,22,20,18,16,14,12,10,8,6,4,2,-24,-22,-20,-18,-16,-14,-12,-10,-8,-6,-4,-2]
ydata_raw =[0.398,0.061,0.066,0.076,0.095,0.115,0.148,0.183,0.211,0.270,0.330,0.361,0.391,0.061,0.066,0.076,0.095,0.115,0.148,0.183,0.211,0.270,0.330,0.361,0.391]
y_norm = []
for i in range(len(ydata_raw)):
temp = ydata_raw[i]/0.398
y_norm.append(temp)
plt.plot(xdata_raw, y_norm, 'o')
xdata = np.asarray(xdata_raw)
ydata = np.asarray(y_norm)
def Gauss(x, A, B):
y = A*np.exp(-1*B*x**2)
return y
parameters, covariance = curve_fit(Gauss, xdata, ydata)
fit_A = parameters[0]
fit_B = parameters[1]
fit_y = Gauss(xdata, fit_A, fit_B)
plt.plot(xdata, ydata, 'o', label='data')
plt.plot(xdata, fit_y, '-', label='fit')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
plt.legend()
plt.xlabel('Winkel der Auslenkung in °')
plt.ylabel('Intensität [I]')
plt.title('vertikale Ausrichtung')
GaussFit()
so this is the funktion and i got this plot:enter image description here
as you can see, its not high quality. Im trying to fit my data to a gauss-kurve and norm it to 1. but it seems numpy got a problem with the range of the numbers. Any ideas how to fix it and get a reasonable plot?
CodePudding user response:
y = A*np.exp(-1*B*x**2)
Maybe try
y = A*np.exp(-1*B*np.square(x))
Or look at Python RuntimeWarning: overflow encountered in long scalars for a similar exception. Might be that you have to use a 64 bit type for y.
CodePudding user response:
Okay its solved, it wasnt the issue in the exp-funktion in particular. The problem is solved by addin a np.linspace() funktion that (as i think) is providing the limitations that are needed to generate the plot. as followed:
fit_y = Gauss(xdata, fit_A, fit_B)
x = np.linspace(-25, 25, 1000)
plt.plot(xdata, ydata, 'o', label='data')
plt.plot(x, Gauss(x, fit_A, fit_B), '-', label='fit')