'How to fix the error: takes 1 positional arguments but 2 were given?

Problem: I would like to fix the error below. f() takes 1 positional arguments but 2 were given My code:

import math

delta_x = 0.001

def integrate(func, z, w):
  return func(z, w)

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


Solution 1:[1]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BlackBeans