Skip to content

Instantly share code, notes, and snippets.

@tymofij
Created July 1, 2015 12:22
Show Gist options
  • Save tymofij/04a4e83bd562b90b24f3 to your computer and use it in GitHub Desktop.
Save tymofij/04a4e83bd562b90b24f3 to your computer and use it in GitHub Desktop.
div w/o div
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