max function within integrate.quadrature fails
Question:
The following basic Python script fails:
from scipy import integrate
integrate.quadrature(lambda t: max(1,t), -2, 2)[0]
with the error message:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
It looks to me that the integrate.quadrature
command does not like the max
function but I do not understand why.
Answers:
scipy
is not passing a scalar or 1-element array to your function, so it needs to be vectorized:
from scipy import integrate
import numpy as np
integrate.quadrature(lambda t: np.maximum(1, t), -2, 2)[0]
You will get a warning like
AccuracyWarning: maxiter (50) exceeded. Latest difference = 6.366377e-04
However, the result will be close to the expected value of 4.5:
4.499480255789206
Here is a plot for reference:
t = np.linspace(-2, 2, 100)
plt.plot(t, np.maximum(1, t))
The following basic Python script fails:
from scipy import integrate
integrate.quadrature(lambda t: max(1,t), -2, 2)[0]
with the error message:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
It looks to me that the integrate.quadrature
command does not like the max
function but I do not understand why.
scipy
is not passing a scalar or 1-element array to your function, so it needs to be vectorized:
from scipy import integrate
import numpy as np
integrate.quadrature(lambda t: np.maximum(1, t), -2, 2)[0]
You will get a warning like
AccuracyWarning: maxiter (50) exceeded. Latest difference = 6.366377e-04
However, the result will be close to the expected value of 4.5:
4.499480255789206
Here is a plot for reference:
t = np.linspace(-2, 2, 100)
plt.plot(t, np.maximum(1, t))