How to use user input as the function for a numeric integration algorithm?

Viewed 104

I found an algorithm that calculates the area under the curve of a function using Riemann's sum, also known as approximation by rectangles. However, i have to change the function inside the algorithm everytime i want to calculate a different function. In the code below, the algorithm is set to calculate the area under the curve of x**2.

# Calcuate the area under a curve
#
# Example Function y = x^2
#
# This program integrates the function from x1 to x2
# x2 must be greater than x1, otherwise the program will print an error message.
#
x1 = float(input(’x1=’))
x2 = float (input(’x2=’))
if x1 > x2:
    print(’The calculated area will be negative’)
# Compute delta_x for the integration interval
#
delta_x = ((x2-x1)/1000)
j = abs ((x2-x1)/delta_x)
i = int (j)
print(’i =’, i)
# initialize
n=0
A= 0.0
x = x1
# Begin Numerical Integration
while n < i:
    delta_A = x**2 * delta_x
    x = x + delta_x
    A = A + delta_A
    n = n+1
print(’Area Under the Curve =’, A)

I've tried asking user to input a function like, lets say exp((x** 2)-x) * sin(x**3) from x1 = 1 to x2 = 2.5, but it doesnt work, it displays an error message of invalid syntax. Tried using eval(input(...)) method and it calculated, but it gave the wrong answer (1.2612...). The correct answer for this problem is 2.397...

It is an inconvenience having to rewrite the function in the algorithm, it is not practical to the user.

Can anyone help me please?

1 Answers

As @Tarik commented, check your code's logic first.

Then Try eval(), an example could be:

from math import exp,sin


def integration(func_string, x1, x2):
    reverse = 0
    if x1 > x2:
        print('The calculated area will be negative')
        reverse = 1
        x1, x2 = x2, x1

    delta_x = (x2 - x1) / 1000
    # initialize
    A = 0.0
    x = x1

    while x <= x2:
        delta_A = eval(func_string) * delta_x
        x = x + delta_x
        A = A + delta_A
    if reverse == 1:
        A = -A
    print('Area under the curve', A)


if __name__=='__main__':
    x1 = float(input('x1='))
    x2 = float(input('x2='))
    integration('exp((x** 2)-x) * sin(x**3)', x1, x2)

The example I/O:

x1=1
x2=2.5
Area under the curve 2.395500858985482
Related