在学校里,我们学会了把小数转换成二进制数,还有一个技巧就是把小数位后的数字转换成二进制数。在Python 3中做同样的事情有什么简略吗?
发布于 2018-08-02 13:57:44
他们在学校教你的方式可能是这样的:
def binary(num, digits):
if num == 0:
return '0'
# Figure out biggest power of two greater than the input
position = int(math.log2(num))
result = ''
# Work down in powers of two up to the specified digit
while position >= -digits:
unit = 2**position
if position == -1:
result += '.'
if num >= unit:
result += '1'
num -= unit
else:
result += '0'
position -= 1
return result
这是一个非常简单的实现,清楚地说明了逻辑。
然而,如果你“只是”想要答案,你可以使用更多的内置方法。
def binary2(num, digits):
onezero = f'{int(num*2**digits):b}'
return f'{onezero[:-digits]}.{onezero[-digits:]}'
这就是输出的样子:
examples = [1.5, 1.25, 4.1]
for e in examples:
print(f'{e:>12.4f} -> {binary(e, 4):>12} {binary2(e, 4):>12}')
1.5000 -> 1.1000 1.1000
1.2500 -> 1.0100 1.0100
4.1000 -> 100.0001 100.0001
100.0000 -> 1100100.0000 1100100.0000
100.1250 -> 1100100.0010 1100100.0010
发布于 2018-08-02 15:28:07
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))
This is what i founded. you can also refer this link for proper code
https://www.geeksforgeeks.org/python-program-to-convert-floating-to-binary/
https://stackoverflow.com/questions/-100001875
复制相似问题