Warum ist mein Code für die Generierung einer Kurvenanpassung eines Cosinus für eine Summe von Gaußern, die so schlecht Python

Python-Programme
Anonymous
 Warum ist mein Code für die Generierung einer Kurvenanpassung eines Cosinus für eine Summe von Gaußern, die so schlecht

Post by Anonymous »

Ich habe diesen Code, in dem ich versuche, scipy.optimize.curve_fit () zu verwenden, um eine COS^2 (x) -Funktion zu übernehmen und sie als Summe von Gaußschen Peaks zu nähern. Es erzeugt jedoch eine schlechte Passform und ich kann nicht sagen, warum. Kann mir jemand helfen, das Problem zu identifizieren? < /P>

Code: Select all

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

k = 1
m = 3
x_begin = -m * np.pi / (2*k)
x_end = m * np.pi / (2*k )
x = np.linspace(x_begin, x_end,1000)

cosine_function = np.cos(k * x)**2

def gauss(x,x_0,s):
return np.exp( - (x-x_0)**2 / (2*s**2))

def gauss_approx(x,x_0,s,d,n):
gaussians = 0
for j in range(0,int(n)):
x_0_j = x_0 + j * d
gaussians += gauss(x,x_0_j,s)
return gaussians

result = curve_fit(gauss_approx, x, cosine_function)[0]

x_0 = result[0]
s = result[1]
d = result[2]
n = int(result[3] )

gaussian_approximation = 0
for j in range(0, n):
x_0_j = x_0 + j * d
gaussian_approximation += gauss(x,x_0_j, s)

fig, ax = plt.subplots()
ax.plot(x, cosine_function, label = 'cosine function')
ax.plot(x, gaussian_approximation, label = 'gaussian approximation to cosine')
ax.set_xlabel('x')
ax.set_ylabel('Amplitude')
plt.grid()
plt.legend()
plt.show()

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post