I saw this formula: http://tutorial.math.lamar.edu/Classes/CalcI/ProofIntProp.aspx#Extras_IntPf_AvgVal and tried to implement python algorithm to approximate integrals. It kinda works, but does not make sense to me, so if any1 can explain why, it will be nice :) This is my code:
import random
def monte_carlo(function, a, b, iter = 100000):
"""
function - 2d array of numbers, example: [[2, 1], [5, 4]] 2x^1 + 5x^4
a, b - boundaries
Approximates integral
"""
answer = 0
for i in range(0, iter):
rpt = random.randrange(a, b+1)
print(i , 'th ' , 'iteration')
answer += evall(function, rpt)
return (1/(b-a))*answer
def evall(function, point):
result = 0
for term in function:
result += term[0]*pow(point, term[1])
return result
print('Answer is: ', monte_carlo([[1, 2]], 1, 100))
and it works. But the formula says that we need the delta X in there, so if I make:
deltaX = (b-a)/iter
and then multiply evall(function, rpt) by it, it should work as well, but it does not. The example I used is for the function x^2.