#------------------------------ # PROBLEM 1 #------------------------------ # Write a function integrate(f, a, b, n=1000) # which accepts a real function f(x) (x float variable), interval points a and b, and an optional division number. # It should compute the definite integral of f(x) over the interval (a,b) as a Rieman sum approximation. # Try to test it for x**3 and x**3*sin(x). # SOLUTION: #---------------------------------------------- def integrate(f, a, b, n=1000): dx = float(b-a)/n s = 0 for i in range(n): x = a + i*dx s += f(x) return s * dx # EXAMPLE USAGE #---------------------------------------------- import math def f1(x): return x**3 def f2(x): return x**3 * math.sin(x**2) def f3(x): return x**0.5 * math.e ** (x ** 0.25) def test(): print integrate(f1, 0.0, 5.0, 100) print integrate(f2, 1.0, 4.0, 200) print integrate(f2, 1.0, 4.0, 10000) print integrate(f3, 2, 8, 10000) print integrate(f3, 2, 8, 100000) print integrate(f3, 2, 8, 1000000) if __name__ == "__main__": test()