【发布时间】:2020-08-07 07:26:11
【问题描述】:
如何在 Python 中将 1.942890293094024e-15 或 2.8665157186802404e-07 等小浮点值转换为二进制值?
我试过GeeksforGeek's solution,但是,它不适用于这么小的值(我收到此错误:ValueError: invalid literal for int() with base 10: '1.942890293094024e-15' )。
目前的代码如下所示:
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
【问题讨论】:
-
什么不起作用?您可以复制粘贴代码(最小工作示例)和错误消息吗?
-
我收到此错误:ValueError: invalid literal for int() with base 10: '1.942890293094024e-15'。我把代码放到这个问题上。
-
看看这个trinket。您可能需要进行一些调整。
-
我调整了您发送的代码,它可以工作!非常感谢! @kartoon
-
干得好!如果您发布自己问题的答案以帮助其他需要帮助的人,那将是非常棒的。
标签: python floating-point binary floating