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.
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.