Numerical Integration using random sampling.
Python, 21 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Numerical Integration using random sampling # FB - 201006292 import math import random # define any function here! def f(x): return math.sin(x) # define any xmin-xmax interval here! (xmin < xmax) xmin = 0.0 xmax = math.pi numPoints = 1000000 # bigger the better but slower! sumy = 0.0 for j in range(numPoints): x = xmin + (xmax - xmin) * random.random() sumy += f(x) numInt = (xmax - xmin) * sumy / numPoints print "Numerical integral = " + str(numInt)
What is this? Is it a try to find the worst numerical integration algorithm? If you replace random.random() by equidistant 1.0*j/numPoints you get the integral 2.0. Not to mention the almost trivial Simpson algorithm and much more better more sophisticated algorithms.
I never claimed my algorithm is the best. I only post this thinking some people may find it interesting, that's all.
I also think it would be better if you post the best algorithm code, instead of simply criticizing others!
If you have interest in good algorithms in python, give pygsl and the gsl library in gnu a chance