0

I'm a total beginner in using curve_fit() of scipy. I don't understand what the problem is in the following code of mine:

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

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

xdata = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
ydata = [75,66,63,61,60,58,58,55,56,54,56,59,57,57,56,58,56,58,56,56,56]
popt, pcov = curve_fit(func, xdata, ydata)

It returns RuntimeWarning: overflow encountered in exp

Any idea what could be wrong? Thanks in advance!

3
  • Probably worth putting in a print statement into func to see what arguments it is being called with. Commented Aug 17, 2020 at 15:26
  • @JohanC that didnt help unfortunately Commented Aug 17, 2020 at 16:44
  • @Derlin unfortunately neither, I had seen that one before Commented Aug 17, 2020 at 16:45

1 Answer 1

4

As remarked in this post, np.exp quickly reaches overflow. You can avoid the overflow with adding bounds on b. Note that you only get a warning, and that the result of curve_fit isn't affected.

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

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

xdata = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
ydata = [75, 66, 63, 61, 60, 58, 58, 55, 56, 54, 56, 59, 57, 57, 56, 58, 56, 58, 56, 56, 56]
popt, pcov = curve_fit(func, xdata, ydata, bounds=([-np.inf, 0.0001, -np.inf], [np.inf, 10, np.inf]))
xs = np.linspace(2, 22, 100)
plt.plot(xs, func(xs, *popt))
plt.scatter(xdata, ydata)
plt.show()

example plot

PS: Also note that the fitted function uses the datatype of x, which sometimes causes strange problems. In this example there isn't problem, but in general it could help to add xdata = np.array(xdata, dtype=float) or xdata = np.array(xdata, dtype=np.longdouble).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.