Search code examples
pythonscipycurve-fittingleast-squaresdata-fitting

Fitting data with a complex function in python


I have some data that I am trying to fit with a model

Here's the relevant part of my code

path='D:/ParPhy/2-BESIII15_new.dat'
data = pd.read_table(path,header=None)
y=np.array(data[1])
x=np.array(data[0]**(1/2))
s=x**2
def F_w(s,alpha,m_p,gamma_p):
    P_s=1+alpha*s
    A=-m_p**2
    B=complex(s-m_p**2,m_p*gamma_p)
    return abs(P_s*A/B)**2
popt, pcov = curve_fit(F_w, x, y)

and I keep getting a type error:

"only length-1 arrays can be converted to Python scalars" about "File "D:/PYTHON/Particle Physics/fit_2.py", line 31, in F_w B=complex(s-m_p**2,m_p*gamma_p)"

Any help would be greatly appreciated.


Solution

  • The function complex receives a scalar and you're passing a numpy array. You have to apply the complex function to each element of the arrays like that:

    B = np.zeros(m_p.size, dtype=np.complex)
    for i in range(m_p.size):
        B[i] = complex(x[i], y[i])