python – scipy optimize.curve_fit cannot fit a function whose return value depends on a conditional
python – scipy optimize.curve_fit cannot fit a function whose return value depends on a conditional
Thats right, t < T
is a boolean array. NumPy refuses to assign a truth value to boolean arrays because there are many possible choices — should it be True if all elements are True, or if any element is True?
But thats okay. In this case, NumPy provides a nice function to replace the if ... else ...
blocks, namely, np.where:
def func(t, a0, a1, a2, T, tau1, tau2):
return np.where(
t < T,
a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2),
a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) )