Home > database >  I'm getting a nan result on an integral, Python
I'm getting a nan result on an integral, Python

Time:04-11

I am writing a code that is trying to produce the answer to the integral

I have

import math
import sympy as sy

def f(x):
    nume = (x**2)
    denom = (((x**2)-4)*((x**2) 9))
    y = nume/denom
    return y

xInit = 0
xFin = math.inf

x = sy.Symbol("x")
print(sy.integrate(f(x), (x, xInit, xFin)))

However, when this code is ran I get the result of nan when i am expecting ((3*pi)/26) as the printed results.

How do I fix this?

CodePudding user response:

How do I fix this?

In one sense you don't: there's nothing to fix. The function you give is not integrable (it's neither Riemann integrable nor Lebesgue integrable) over the interval (0, ∞), even with the concept of improper integrals.

In more detail, the function you're trying to integrate isn't defined at x=2; near 2, it has a 1/x-type singularity. If a meaningful value for the integral existed, it should be equal to the sum of the integral of f from 0 to 2 with the integral of f from 2 to . Both of those can be defined as improper integrals, but the first diverges to -∞ while the second diverges to . The sum therefore isn't well-defined, and any real number is as valid an answer as any other. In other words, NaN or an exception is the only reasonable response that SymPy can give here.

However, all is not lost! You can technically define a Cauchy principal value for this integral, and SymPy has support for computing those principal values. Here's an example:

Python 3.10.4 (main, Mar 25 2022, 07:25:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import Integral, oo
>>> from sympy.abc import x
>>> Integral(x**2 / ((x**2 - 4)*(x**2   9)), (x, 0, oo)).principal_value()
3*pi/26

If you want independent corroboration, try submitting the same integral to Wolfram Alpha. Here's a link to my submission. The result is "integral does not converge", but the Cauchy principal value may also be shown. (There appears to be some indeterminism here: the principal value sometimes shows up and sometimes doesn't, for me.)

  • Related