micropython icon indicating copy to clipboard operation
micropython copied to clipboard

3-arg pow() with negative exponent silently returns 0 instead of computing modular inverse

Open jseop-lim opened this issue 7 months ago • 2 comments

Port, board and/or hardware

Unix port, Linux

MicroPython version

MicroPython v1.27.0

Reproduction

print(pow(2, -1, 4))

[!NOTE] The simplest demonstration would be pow(2, -1, None), where CPython produces the expected result 0.5. However, MicroPython issue #19137 causes pow(x, y, None) to raise TypeError before the negative-exponent code path is even reached, so that example cannot be used here. The reproduction below falls back to a 3-arg form where CPython raises ValueError for non-invertibility, which still exercises the same buggy code path in MicroPython.

Expected behaviour

CPython v3.11.15:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: base is not invertible for the given modulus

Observed behaviour

MicroPython v1.27.0:

0

Additional Information

pow(base, exp, mod) with a negative exponent silently returns 0 instead of computing the modular inverse of base modulo mod (or raising ValueError when the inverse does not exist). This is a CPython compatibility issue.

Root Cause

mpz_pow3_inpl short-circuits any negative exponent by setting dest = 0 and returning, so mp_obj_int_pow3 silently yields 0 for every pow(x, neg_exp, mod) call regardless of whether the modular inverse exists.

// py/mpz.c:1358-1362
void mpz_pow3_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs, const mpz_t *mod) {
    if (lhs->len == 0 || rhs->neg != 0 || (mod->len == 1 && mod->dig[0] == 1)) {
        mpz_set_from_int(dest, 0);
        return;
    }
    ...

CPython's long_pow negates the exponent and calls long_invmod to compute the modular inverse, raising ValueError("base is not invertible for the given modulus") when gcd(base, |mod|) != 1.

CPython reference: Objects/longobject.c#L4455-L4474

// If exponent is negative, negate it and replace the base with
// its modular inverse; long_invmod raises ValueError when gcd != 1.
if (Py_SIZE(b) < 0) {
    temp = (PyLongObject *)_PyLong_Copy(b);
    if (temp == NULL)
        goto Error;
    Py_DECREF(b);
    b = temp;
    temp = NULL;
    _PyLong_Negate(&b);
    if (b == NULL)
        goto Error;

    temp = long_invmod(a, c);
    if (temp == NULL)
        goto Error;
    Py_DECREF(a);
    a = temp;
    temp = NULL;
}

Fix

Replace the rhs->neg != 0 short-circuit in mpz_pow3_inpl with a modular-inverse path (extended Euclidean), change the return type to bool, and raise ValueError("base is not invertible for the given modulus") from mp_obj_int_pow3 when the helper signals a non-invertible base.

Code of Conduct

Yes, I agree

jseop-lim avatar Apr 23 '26 10:04 jseop-lim

I guess it all depends on how much code it takes to compute the value using the same approach as CPython.

This operation probably isn't commonly performed on microcontrollers, so MicroPython's approach for this situation could be classified as "good enough". If you know of any algorithms that need this and that are often used in embedded computing, or situations where this could be needed on a microcontroller, then this could be added but gated behind an optional define (disabled by default or requiring either MICROPY_CONFIG_ROM_LEVEL_FULL_FEATURES or MICROPY_CONFIG_ROM_LEVEL_EVERYTHING to be included).

I haven't checked if MicroPython also behaves the same way when dealing with floating point values. If it does, then patching MPZ code may imply also patching the FP code too to keep things aligned.

Personally, I think this could be solved with a cpydiff entry instead, but that's just me :)

agatti avatar May 17 '26 02:05 agatti

@agatti Sorry for the slow reply. Some answers below.

Floats: already fine — pow(2.0, -1, 4) raises TypeError on both, so there's no FP code to patch. The wrinkle is elsewhere: non-MPZ builds compute pow() as (x ** y) % z (py/modbuiltins.c), so a negative exponent returns a float there — pow(2, -1, 4) gives 0.5 instead of 0. No shipping board hits it (every in-tree port is MPZ, and the ROM_LEVEL_MINIMUM ones have POW3 off), but it does mean the divergence isn't confined to mpz.c.

Implementing it: agreed, not worth it. There's no extended GCD in py/mpz.c to build on — mpz_gcd is inside the #if 0 unused block — so it's a real chunk of new bignum code. And it wouldn't buy much: libraries gate on sys.version_info >= (3, 8) while we report 3.4, so existing portable code would keep using its own extended-Euclid helper regardless.

I did look at just raising ValueError on a negative exponent rather than returning 0, since the current value is silently wrong rather than loudly unsupported. But that would also raise for pow(2, -1, 5), where CPython returns a perfectly good 3 — so it trades one divergence for another instead of removing one. Not worth changing long-standing behaviour for a half-measure.

So: cpydiff it is. The captured output will be the MPZ 0, with a note in the entry that non-MPZ builds return a float instead. PR coming.

jseop-lim avatar Jul 21 '26 06:07 jseop-lim