Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sympy.perfect_power(-64) return False?

The documentation for sympy.perfect_power says:

Return (b, e) such that n == b**e if n is a unique perfect power with e > 1, else False (e.g. 1 is not a perfect power). A ValueError is raised if n is not Rational.

Yet evaluating sympy.perfect_power(-64) results in False. However, -64 == (-4)**3, so sympy.perfect_power(-64) should return (-4, 3) (also because there is no other integer base with integer exponent > 1).

Is this a bug? Or am I missing something here?

like image 821
William Hu Avatar asked Aug 31 '25 03:08

William Hu


1 Answers

At the documentation, click on [source] and you'll find this:

    if n < 0:
        pp = perfect_power(-n)
        if pp:
            b, e = pp
            if e % 2:
                return -b, e
        return False

Given -64, that first computes that 64 is 2^6 and then gives up because 6 isn't odd.

I do think it's a bug and it should try to remove the factor 2 from the exponent. Maybe like this:

    if n < 0:
        pp = perfect_power(-n)
        if pp:
            b, e = pp
            e2 = e & -e
            if e2 != e:
                return -(b**e2), e//e2
        return False
like image 136
no comment Avatar answered Sep 02 '25 17:09

no comment