I wrote a code to compute the integrale of a function of one variable, using the midpoint rule.
import scipy
import numpy as np
from scipy import integrate
from numpy import linspace, sum
a=1
b=1e4
n=100
def f(x):
return 2*x
def midpoint(f,a,b,n):
h=float(b-a)/n
x=linspace(a+h/2, b-h/2,n)
return h*sum(f(x))
It is working. Now i want to use the same approach for f(x,y), where I still just want to integrate over only the x variable, so a 1D integration.
precision: y is not a constant, for example y=linspace(1,10,10). I want to plot (y,integrale of f(x,y) over x).
Any idea ?
PS: thanks to @SUTerliakov a possible solution is
import scipy
import numpy as np
from scipy import integrate
from numpy import linspace, sum
from functools import partial
a=1 #minimum value taken by the variable x
b=1e4 #maximum value taken by the variable x
n=100 #number of points of integration
def f(x,y):
return 2*x*y
def midpoint(g,a,b,n): #g(x) is an arbitrary function
h=float(b-a)/n
x=linspace(a+h/2, b-h/2,n)
return h*sum(g(x))
y_arr=linspace(1,10,10)
for y in y_arr:
f_partial=partial(f,y) #the function f(x,y) for y=cte
print(midpoint(f_partial,a,b,n))
The "for" loop is slow if my function is more complicated and if I want to integrate over a large scale. Is it possible to find a solution without using a "for" loop ?
Thank you.