Problem: Convert the given fractional decimal to binary.
Example:
decimal_to_binary_fraction(.0)
0
decimal_to_binary_fraction(.1)
0.0001100110011001
decimal_to_binary_fraction(.25)
0.01
decimal_to_binary_fraction(.35)
0.0101100110011001
Solution in Python:
import math
def decimal_to_binary_fraction(n, max_digits=16, eps=1e-12):
"""
Author: Mayur P Srivastava
"""
"""
Author: Mayur P Srivastava
"""
assert n >= 0 and n < 1
if n < eps:
return "0"
binary_str = "0."
num_digits = 0
while num_digits < max_digits and abs(n) > eps:
n = n * 2
if n >= 1:
binary_str += "1"
n -= 1
else:
binary_str += "0"
num_digits += 1
return binary_str
Concepts Learned: Single loops, number system
No comments:
Post a Comment