I have been trying to integrate 2x dx from 3 to 4 using SciPy but it is returning an incorrect value.
from scipy.integrate import quad
def g(x):
return (2*(x**2))/2
quad(g,3,4)
The result returned should be 7, but I am getting result as 12.3333
You're providing the antiderivative of the function you intend to integrate, but scipy.integrate.quad()
expects the the function by itself.
In other words, if you want to integrate 2*x, then you should provide 2*x.
However, since you do have the antiderivative, you don't need quad()
at all. You can just evaluate your antiderivative at the beginning and end of your integral's bounds. The quad()
function is most useful when the integral has no known analytic solution.
Here is an example of how to solve this integral, with and without quad()
.
from scipy.integrate import quad
def g(x):
return 2 * x
def g_integral(x):
return (2 * (x**2))/2
print("Integral via numeric integration", quad(g, 3, 4))
print("Integral via analytic solution", g_integral(4) - g_integral(3))