TurtleDave
TurtleDave

Reputation: 55

How to numerically integrate f(x) between a lower and an upper bound?

I have been told to modify the code i had before to integrate between the lower bound a and upper bound b.This is done by adding another parameter, width. The integral can then be calculated by summing up lots of rectangles of with area (width*f(x)). An example of what I need to calculate is shown below

Calculate the integrals of f(x)=x from 0 to 100.

My code I have to modify is this, this is used to calculate product, how do I modify this to calculate integrals?

def product(f, a, b):
    total = 1
    for i in range(a, b+1):
        total *= f(i)
    return total

Upvotes: 0

Views: 611

Answers (2)

Sнаđошƒаӽ
Sнаđошƒаӽ

Reputation: 17612

Edited:

Assuming your function f(x) calculates the functional value at x, you can do something like this:

def f(x): # define this according to your function.
    return x*x

def integrate(func, a, b, width):
    total = 0
    i = a
    while i <= b:
        total += func(i)
        i += width
    return total * width

width = 0.01
integral = integrate(f, 0, 100, width)
print(integral)

Output:

333283.3350000302

True value of the integral is 333333.333333, so the result is quite accurate.

Edit:

To use some other functions like sin or cos, you can use built-in functions, inside the function f(x) like this:

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

Then to integrate from 0 to pi, use this:

width = 0.01
integral = integrate(f, 0, math.pi, width)
print(integral)

Remember to import math using import math.

Upvotes: 1

Miles
Miles

Reputation: 100

If your width needs to be something like 0.001, you'll have to use something else than range, as it can't deal with float values.

Try while loop:

def integral(f, a, b, width):
    total = 0
    i = a
    while i <= b:
        total += f(i)
        i += width
    return total*width

EDIT: You can use it like this:

def foo(x):
    return x
a = 0
b = 1
width = 0.001

integrated = integrate(foo, a, b, width)
print(integrated)

Note that you don't have to declare a, b, and width as variable; You can just pass them in directly.

Upvotes: 1

Related Questions