Programming Language Python: The function has this signature def print_binary (n
ID: 3733562 • Letter: P
Question
Programming Language Python:
The function has this signature def print_binary (number_string, fraction_length) Print the binary version of the decimal number string. The decimal string is guaranteed to be valid as in Program 3. The printed binary number must have at least one digit before and after the ".". The fraction length parameter is the number of binary digits to print after the"." Unlike Program 2 you do NOT round the binary fraction at the last digit. Positive numbers should be printed with a sign. If the number is 0 and the fraction length is 4 the output would be: +0.0000 If the decimal number is -12.4 and the fraction length is 10 the output would be -1100.0110011001Explanation / Answer
Function for conversion of given value to binary number stored as string
import math
def print_binary(i,l):
num=i
s = ''
n= num - math.floor(num)
if int(i) == 0:
s="0"
else:
while int(i):
if int(i) & 1 == 1:
s = "1" + s
else:
s = "0" + s
i /= 2
s=s+"."
for x in range(l):
n=n*2
nr = n - math.floor(n)
n=n-nr
if n==1:
s = s + "1"
else:
s = s+ "0"
if(num<0):
print "-"+ s
else:
print "+" + s
return s
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.