1

I'm trying to use Python's curve_fit to fit a function to some data.

I have a function

y = aln(bx + 1)

where a and b are constants to be found, y is the dependant variable and x is the dependant variable.

The data for x and y are given by xdata and ydata respectively.

So far I have the following code:

def func(x, a, b):
     return a * np.log(x * b + 1)

popt, pcov = curve_fit(func, xdata, ydata, maxfev = 5000)

However when running the code, I get the error:

RuntimeWarning: invalid value encountered in log return a * np.log(x * b + 1)

Which I believe is due to the fact that curve_fit is trying negative values inside the log.

How can I prevent curve_fit from trying negative numbers and throwing up the error? Is there another way to approach this?

1 Answers1

0

if curve_fit iterates a single value each time just add a max() check:

 a * np.log(max(0,x * b + 1))

if it does it from a numpy array, you can change negative values with a boolean mask:

X = x * b + 1
boolean_mask = (x * b + 1)<0
X[boolean_mask] = 0
Guinther Kovalski
  • 1,629
  • 1
  • 7
  • 15
  • Thanks v much! I had a go at doing this but unfortunately this lead to negative values of b sometimes being chosen! – Hallonmallic Mar 20 '22 at 12:00
  • @Hallonmallic : One cannot help if no numerical example is provided in order to peproduce and study a case where the difficulty occurs. – JJacquelin Mar 22 '22 at 08:16