Search code examples
pythonscipycurve-fittingdata-fitting

scipy.optimize.curve_fit raises RuntimeWarning


I am trying to fit a curve by changing two parameters (e and A). The target curve is plotted by assigning n0=0.395, but its actual value is 0.0395. So I am hoping to achieve the same curve by changing e and A.

import numpy as np
from scipy.optimize import curve_fit

def func(x,e,A):
    return A*(e+x)**0.0395 

strain = np.linspace(0,15,3000) # variable
e = 0.773
A = 386.5
n0 = 0.395
y = A*(e+strain)**n0 # target to minimize
popt, pcov = curve_fit(func, strain, y)

However, I constantly get this warning after running the code:

RuntimeWarning: invalid value encountered in power
  return A*(e+x)**0.0395

I was wondering why this happens and how should improve the code?


Solution

  • I found a solution that I do not like, but it does eliminate the warning. I found that, strangely to me, "e" was being made negative within curve_fit(). I added a "brick wall" inside the function to stop this, but it should be unnecessary. My code is:

    import numpy as np
    from scipy.optimize import curve_fit
    
    def func(x,e,A):
        if e < 0.0: # curve_fit() hits a "brick wall" if e is negative
            return 1.0E10 # large value gives large error, the "brick wall"
        return A*(e+x)**0.0395 
    
    strain = np.linspace(0,0.1,3) # variable
    e = 0.773
    A = 386.5
    n0 = 0.395
    y = A*(e+strain)**n0 # target to minimize
    popt, pcov = curve_fit(func, strain, y)