Last active
November 15, 2018 16:51
-
-
Save RustemB/a1de68aafd72e6e32239252d47611671 to your computer and use it in GitHub Desktop.
Convert decimal to binary
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
from decimal import Decimal as D | |
from math import pi, e | |
def convert(n, d=8): | |
""" | |
convert decimal to binary | |
""" | |
res = bin(int(n))[2:] + "." | |
x = D(n - int(n)) | |
while d != 0: | |
x *= 2 | |
res += str((x % 2).to_integral_value()) | |
d -= 1 | |
return res | |
tests = [1.5, 3.65, 12.12, pi, e] | |
for test in tests: | |
print(convert(test)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment