Last active
December 28, 2015 20:29
-
-
Save pyrocat101/7558259 to your computer and use it in GitHub Desktop.
Float number powered by an integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def my_pow(a, b): | |
""" | |
Returns the value of the `a` raised to the power of `b`. | |
Assume that `a` is a float number and `b` is an integer. | |
Special cases: | |
* if `b` is zero, then result is 1.0 | |
* if `a` is NaN and `b` is non-zero, then the result is NaN. | |
* if `a` is 0 and `b` < 0, or `a` is +Inf and `b` > 0, then the | |
result is +Inf. | |
* if `a` is -0.0 and `b` > 0 and `b` is not a finite odd | |
integer, or if `a` is -Inf and `b` < 0 and `b` is not a finite | |
odd integer, then the result is +0.0 | |
* if `a` is -0.0 and `b` > 0 and `b` is a positive finite odd | |
integer, or `a` is -Inf and `b` < 0 and `b` is a finite odd | |
integer, then the result is -0.0 | |
* if `a` is -0.0 and `b` < 0 and not a finite odd integer, or | |
`a` is -Inf and `b` > 0 but not a finite odd integer, then | |
the result is +Inf. | |
* if `a` is -0.0 and `b` < 0 and is a finite odd integer, or `a` | |
is -Inf and `b` is a positive finite odd integer, then the | |
result is -Inf. | |
>>> my_pow(42, 0) | |
1.0 | |
>>> my_pow(float('nan'), 42) | |
nan | |
>>> my_pow(0.0, -1) | |
inf | |
>>> my_pow(float('inf'), 42) | |
inf | |
>>> my_pow(-0.0, 2) | |
0.0 | |
>>> my_pow(float('-inf'), -2) | |
0.0 | |
>>> my_pow(-0.0, 3) | |
-0.0 | |
>>> my_pow(float('-inf'), -3) | |
-0.0 | |
>>> my_pow(-0.0, -42) | |
inf | |
>>> my_pow(float('-inf'), 42) | |
inf | |
>>> my_pow(-0.0, -3) | |
-inf | |
>>> my_pow(float('-inf'), 3) | |
-inf | |
>>> my_pow(2, 42) | |
4398046511104.0 | |
""" | |
a = float(a) | |
b = int(b) | |
if b == 0: | |
return 1.0 | |
if math.isnan(a): | |
return a | |
# reciprocal | |
if b < 0: | |
b = -b | |
a_sign = math.copysign(1.0, a) | |
if a == 0: | |
a = a_sign * float('inf') | |
else: | |
a = 1 / a | |
# do the math | |
ret = 1.0 | |
while b > 0: | |
if b & 1: | |
ret *= a | |
b >>= 1 | |
a *= a | |
return ret | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment