Max Jackson
Max Jackson

Reputation: 1

How do i get the curve_fit to fit the data?

I can't figure out why my curve_fit is not following the data?

import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
import math
from scipy.stats import binom, poisson, norm
from scipy.optimize import curve_fit

AD1 = sio.loadmat('ATLAS_DATA1' ,squeeze_me=True,mat_dtype = True)
locals().update({k :AD1[k]for k in ['n','e']})

xData = e
yData = n
yErr = 0
plt.xlabel("e (GeV)")
plt.ylabel("Number of events (n)")
plt.errorbar(xData,yData,yErr,marker = '.',linestyle = '')
plt.show()

def func(e, a, b):
    return a * np.exp(-b * e)

xDat = e
yDat = func(xDat, 2, 1)
popt, pcov = curve_fit(func, xDat, yDat)
plt.plot(xDat, func(xDat, *popt))
plt.show()

Below is my data for n at the top and e at the bottom. Data for n and e

Graph for the data that i want to fit

Upvotes: 0

Views: 88

Answers (1)

Bhbf
Bhbf

Reputation: 187

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

Write your xData and yData as numpy arrays as follows:

I used a sample from it

xData =np.array([383,358,326,366,335,331,308,299,303,325,306,299,270,282,253,265,248,256,220,208,252,215,220,237,204,213,224,212])
yData = np.array([101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,124,128])
plt.xlabel("e (GeV)")
plt.ylabel("Number of events (n)")
plt.scatter(xData,yData)
plt.show()

Heres the original data

enter image description here

Its bettter to use plt.scatter than plt.errorbar

i found this equation better for your curve

  def func(x, a, c, d):
    return a*np.exp(-c*x)+d

Same thing goes for xDat (write it as np.array)

xDat = xData
yDat = func(xDat, 2, 1)
plt.scatter(xDat,yDat)
popt, pcov = curve_fit(func, xData, yData,p = (10, 1e-6, 100))
plt.plot(xDat, func(xDat, *popt))
plt.show()

enter image description here

Tip: Dont use lower case e as a variable, because most of the time e represents the exponential constant e=2.77

UPDATE :

if you want to use your original function heres the code:

def func(e, a, b):
    return a * np.exp(-b * e)
 popt, pcov = curve_fit(func, xData, yData,p0 = [10,-0.00001])

Upvotes: 1

Related Questions