(PYTHON PROGRAMMING) The function has this signature: def print_binary(number_st
ID: 3733241 • Letter: #
Question
(PYTHON PROGRAMMING)
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.0110011001
Explanation / Answer
def print_binary(number_string, fraction_length): if number_string[0] == '-': print("-",end="") number_string = number_string[1:] else: print("+",end="") if number_string.find('.') != -1: #if decimal contrains fraction nums = number_string.split(".") #split into two halves x = int(nums[0]) #x stores first half print("%s."%int(bin(x)[2:]),end="") #convert it into binary from fract = "0." + nums[1] #fract stores second half like "0.4" for i in range(0, fraction_length): #iterates till end of fraction length fract = 2 * float(fract) #multiplies fract part with 2 if float(fract) == 1.0: #if fraction part is 1 print("1",end="") #the print 1 fract = 0 #and set it to 0, so that only 0's will print elif float(fract) > 1: #if fraction part is greater than 1 print("1",end="") #print 1 and subtract 1 from it fract = float(fract) - 1.0 elif float(fract) < 1: #if its lesser than 1 then print 0 print(0,end="") else: print(0,end="") #print 0's in case fract becomes 0 else: if int(number_string) == 0: print("0.",end="") else: x = int(number_string) print("%s."%int(bin(x)[2:]),end="") for i in range(0, fraction_length): print("0",end="") print() test_values = "0 1234 -124 -12.4".split() for number in test_values: print(number, end=': ') print_binary(number, 10)Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.