-1

Here is my exmaple:

pow(100, -1 , 321) # output 61
pow(100, -1) % 321 # output 0.01
100 ** -1 % 321 # output 0.01

I know that pow(x, y, z) should be equal to pow(x, y) % z or x ** y % z, but in my case it's not.

This answer said it's because x ** y is too small, but in my case it's not that small at all.

Can anyone explain?

I would appreciate.

L-ING
  • 13
  • 2
  • See [_How does Python pow() function work with a negative power and a mod value_](https://stackoverflow.com/q/63801527/674039) – wim Aug 14 '23 at 02:04
  • @wim I didn't find your answer before. My bad. – L-ING Aug 14 '23 at 04:29

1 Answers1

4

A third argument to pow() is supported only if all arguments are of integer type. In that case, pow(i, j, k) computes the number-theoretic value of i to the j'th power in the multiplicative group of integers modulo k. You don't need this unless you need it, and then you really need it ;-)

A power of -1 in this context means to compute the multiplicative inverse of i modulo k, or, in other words, the integer m in range(k) such that i*m is congruent to 1 modulo k. In the example you gave,

>>> 61 * 100
6100
>>> _ % 321
1

so 61 is the multiplicative inverse of 100 modulo 321. If a multiplicative inverse exists, it's unique (modulo k). If it doesn't exist, pow() raises an exception:

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

Don't care about any of this? That's fine. Someday you might. In the meantime, stick to the ** operator for raising floats to powers. 3-argument pow() was really designed as a convenient way to access advanced algorithms for integers.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
  • Thank you for your explanation.I need to use this in a crypto algorithm. But my embedded machine is 32bit so the result is different. So I have to use Decimal to simulate it. Now I know it. Thank you very much. – L-ING Aug 14 '23 at 03:07
  • The value of modular integer pow for given arguments should be the same regardless of the machine ;you're running on. If you have a case where it isn't, please open a different topic giving the exact inputs and outputs you're seeing. – Tim Peters Aug 14 '23 at 03:14
  • 1
    I'm simulating on wokwi, here is the example [link](https://wokwi.com/projects/373006465140859905). Press the play button to start. – L-ING Aug 14 '23 at 04:03
  • You should open a new issue with a "micropython" tag. I don't know anything about it. But "it's a bug" if it doesn't compute modular inverses correctly - assuming (I don't know) that this isn't a documented restriction in MicroPython. – Tim Peters Aug 14 '23 at 04:12
  • Ok. But still thanks to you, I can continue on my work. Really appreciate. – L-ING Aug 14 '23 at 04:18