Search code examples
pythonsympymathematical-expressions

Why sympy cannot calculate fraction power formula like (6-x*x)**(1.5)?


I used sympy to calculate some integral as follows.

#Calculate Calculus
import sympy
x = sympy.Symbol('x')
f = (6-x*x)**(1.5)
f.integrate()

This will fail and throw excepiton like:

ValueError: gamma function pole

It works fine if I just use an integer as power num

f = (6-x*x)**(2)
#result: x**5/5 - 4*x**3 + 36*x

Solution

  • My guess is a 1.5 expression is treated as a floating point, which is imprecise. You'd want a symbolic (exact) representation, instead. (I would guess if you were after a computational integral a floating point would probably be okay, generally, as a math library that supports a computational integral would typically use an integral approximation method to compute the integral.) If you need to do arbitrary rational exponents, consider using sympy.Rational. Here's a relevant answer on StackOverflow that seems to support this. I think the documentation for sympy.Rational is here. You can try this modified code here:

    #Calculate Calculus
    import sympy
    frac = sympy.Rational
    x = sympy.Symbol('x')
    f = (6-x*x)**(frac('1.5'))
    f.integrate()