Created
July 1, 2015 12:22
-
-
Save tymofij/04a4e83bd562b90b24f3 to your computer and use it in GitHub Desktop.
div w/o div
This file contains hidden or 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
from math import log, e, copysign | |
def div(x, y): | |
""" divide x by y without using / operator | |
""" | |
sign = x * y | |
res = e ** (log(abs(x)) - log(abs(y))) | |
res = copysign(res, sign) | |
rounded = int(round(res)) | |
if rounded * y == x: | |
return rounded | |
else: | |
return res | |
assert div(4, 2) == 2 | |
assert div(10, 2) == 5 | |
assert round(div(5,2) * 10) == 25 | |
assert div(-4, 2) == -2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment