Search code examples
pythonpython-3.xsicp

Approximate the Riemann sum with comprehensions


I am following the sicp to compute the integral with Riemann sum:

#+begin_src ipython :session sicp :results output
def integral(f, a, b, dx):
    add_dx = lambda x: x + dx
    return sum_recur(f, a+(dx/2), add_dx, b) * dx

from functools import lru_cache
@lru_cache(maxsize=None)
def sum_recur(term, a, next, b):
    if a > b: return 0
    return term(a) + sum_recur(term, next(a), next, b)

def cube(x): return x ** 3

print(integral(cube, 0, 1, 0.01))

#+end_src

#+RESULTS:
: 0.24998750000000042

It works properly, but when implement it with list comprehension

#+begin_src ipython :session sicp :results output
def integral(f, a, b, dx):
    return sum(a+dx/2+n*dx for n in range(b-1)) * dx
print(integral(cube, 0, 1, 0.001))
#+end_src

#+RESULTS:
: 5e-07

It does not work as expected, what's the problem?


Solution

  • In your example, the range(a-b) part is evaluating range(-1). Also, you aren't calling your cube function anywhere.

    Try this:

    def cube(x): return x ** 3
    
    def integral(f, a, b, dx):
        return sum(f(a+dx/2+n*dx) for n in range(int((b-a)/dx)) ) * dx
    
    print(integral(cube, 0, 1, 0.01))
    

    Prints:

    0.24998750000000006