mercredi 19 mai 2021

Defining a mathematical function containing an if statement in Python [closed]

I would like to define the following function in Python.

function

How should I do it?

I have tried the following:

def sphere (x, c, a, n):
  if x <= a:
   return c * ((3*x/2*a) - 0.5*((x/a)**3))+n 

  else:
    return c + n

but when I apply it to a .curve_fit I get the following error:

spht, sphcov = curve_fit(sphere, xdata, data, bounds=(0, [10000, 10000, 10000]))

>>>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-78-e3325b312615> in <module>()
      1 #popt, pcov = curve_fit(exp, df['bin_center'], df['gamma'], bounds=(0, [100., 100., 100.]))
      2 #gaust, gauscov = curve_fit(gaus, df['bin_center'], df['gamma'], bounds=(0, [100., 100., 100.]))
----> 3 spht, sphcov = curve_fit(sphere, df['bin_center'], df['gamma'], bounds=(0, [100., 100., 100.]))

5 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in __nonzero__(self)
   1328     def __nonzero__(self):
   1329         raise ValueError(
-> 1330             f"The truth value of a {type(self).__name__} is ambiguous. "
   1331             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1332         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Aucun commentaire:

Enregistrer un commentaire