0

I need to write a python code to calculate the exact value of the integral (-5, 5) of 1/(1+x^2). I know the answer is 2arctan(5) which is roughly equivalent to 2.746801...

I have below the code I have written, however I am getting a slightly different answer and I was wondering if there is anything I can do to make this code more accurate? Thanks for any help!

## The function to be integrated
def func(x):
    return 1/(1 + x**2)


## Defining variables
a = -5.0
b = 5.0
dx = 1.0
Area = 0


## Number of trapezoids
n = int((b-a)/dx)

## Loop to calculate area and sum
for i in range(1, n+1):
    x0 = a + (i-1)*dx
    x1 = a + i*dx

    ## Area of each trapezoid
    Ai = dx*(func(x0) + func(x1))/2.0

    ## Cumulative sum of areas
    Area = Area + Ai

print("The exact value is:  ", Area)

The answer I am getting is 2.756108... I know it's a small difference, however, it is a difference and I would like to try for something more exact.

Katherine
  • 1
  • 1

1 Answers1

1

The reason you are getting an approximate value for the integral is because you are using an approximation technique (a first-order approximation to compute the value of the definite integral).

There are two ways to evaluate an integral: analytically or numerically (by approximation). Your method is of the second variety, and since it's an approximation it will generate a value that is within a certain margin of error of the real value.

The point of my answer is that there is no way for you to calculate the exact value of the integral using a numeric approach (definitely not in the case of this function). So you will have to settle for a certain margin of error that you're willing to accept and then choose a delta-x sufficiently small to get you within that range.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151