Home > Mobile >  How to implement a single integral of Riemann sums using the following conditions?
How to implement a single integral of Riemann sums using the following conditions?

Time:04-03

Problem: I would like to implement the function integrate(func, a, b). func is a function, a and b are floats which are the start and endpoints in which I have to evaluate the integral. The code should print 0.460. I set Δx equal to 0.001. Aside from the error below, I know the code is still lacking something. What should I add? This is Riemann sums, btw.

My code:

import math

delta_x = 0.001

def integrate(func, a, b):
  return func(a, b)

def f(x):
  return math.sin(x)

i = integrate(f, 0, 1)
print("{:.3f}".format(i))

#Error: f() takes 1 positional arguments but 2 were given

CodePudding user response:

Since I'm not sure you know what a Riemann integral is, I'll give a short explanation which is going to make the code clear. You can think of an integral as a "continuous average", like taking the average of function rather than of a finite number of values. This suggests that you can approach the integral of a function f over [a, b] with averages of evenly distributed points overs [a, b]. Formally, there is a class of functions for which any sequence of such averages, such as the number of points tends to infinity (and that they are evenly distributed), all converges to a single number, defined as that function's integral over [a, b]. This means that, if the function is Riemann-integrable, it does not matter which points you choose, as long as the step goes to zero.

In practice, we choose a step sufficiently small so that the average we compute is close enough to the real integral. This step is what you have called delta_x. Then, the integral approximation is simply the average of a finite number of values, that is, f taken a points x_k=a delta_x*k*(b-a) with k going from 0 to int(1/delta_x) (you can check that these points are evenly distributed — even though I have not formally defined what it means for points to be evenly distributed, your intuition of what is means should be enough) The code follows easily

def integrate(f, a, b):
    n = int(1/delta_x) # number of steps
    return sum(f(a delta_x*k*(b-a)) for k in range(n))/n

Of course, if you read carefully the definition of the integral, you see that all such averages converge to the integral, not that they all converge equally fast. There are better ways (for instance, approximating the function's area with trapezoid or with quadratics give better results than with a rectangle as we did).

  • Related