如何将较小的浮点值(例如1.942890293094024e-15或2.8665157186802404e-07转换为Python中的二进制值?
我尝试过GeeksforGeek's solution,但是对于如此小的值不起作用(我收到此错误:ValueError:int()的无效文字,基数为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
经过一番咨询,我找到了可以解决我问题的好piece of code。我只需要对其进行一些调整(使其成为功能,删除自动输入请求等)。
非常感谢@kartoon!
我看到的一个问题是str(number).split(".")
。在此之前,我添加了一个简单的技巧:number = "{:30f}".format(number)
,因此没有e
的数量。不过,我不确定结果是否正确。