Python没有提供任何内置方法来轻松将浮点十进制数转换为二进制数。因此,让我们手动执行此操作。
方法 :
要将浮点十进制数转换为二进制,请先将整数部分转换为二进制形式,然后将小数部分转换为二进制形式,最后将两个结果组合起来得出最终答案。
对于整数部分,请继续将数字除以2,然后记下余数,直到和除非股息小于2。否则,请停止并将所有余数一起复制。
对于小数部分,请保持小数部分与2的乘积,直到和除非剩下0作为小数部分。第一次相乘后,记下整数部分,然后再次将新值的小数部分乘以2。一直这样做,直到达到完美的数字为止。
Above steps can be written as :
1(base 10) = 1(base 2) and .234(base 10) = .0011(base 2)
Now, to get the binary of 1.234, merge both results as a complete number.
(1)10 = (1)2
[approx.]
(.234)10 = (.0011)2
(1.234)10 = (1.0011...)2
(1.234)10 = (1.0011)2
下面是实现:
# Python program to convert float
# decimal to binary number
# Function returns octal representation
def float_bin(number, places = 3):
# split() seperates whole number and decimal
# part and stores it in two seperate variables
whole, dec = str(number).split(".")
# Convert both whole number and decimal
# part from string type to integer type
whole = int(whole)
dec = int (dec)
# Convert the whole number part to it's
# respective binary form and remove the
# "0b" from it.
res = bin(whole).lstrip("0b") + "."
# Iterate the number of times, we want
# the number of decimal places to be
for x in range(places):
# Multiply the decimal value by 2
# and seperate the whole number part
# and decimal part
whole, dec = str((decimal_converter(dec)) * 2).split(".")
# Convert the decimal part
# to integer again
dec = int(dec)
# Keep adding the integer parts
# receive to the result variable
res += whole
return res
# Function converts the value passed as
# parameter to it's decimal representation
def decimal_converter(num):
while num > 1:
num /= 10
return num
# Driver Code
# Take the user input for
# the floating point number
n = input("Enter your floating point value : \n")
# Take user input for the number of
# decimal places user want result as
p = int(input("Enter the number of decimal places of the result : \n"))
print(float_bin(n, places = p))
输出 :
Enter your floating point value :
1.234
Enter the number of decimal places of the result :
4
1.0011
Enter your floating point value :
11.234
Enter the number of decimal places of the result :
4
1011.0011