Python中小浮点值的二进制表示
如何将较小的浮点值(如1.942890293094024e-15或2.8665157186802404e-07)转换为Python中的二进制值 但是,我尝试过,它对这么小的值不起作用(我得到以下错误:ValueError:invalid literal for int(),以10为基数:“1.942890293094024e-15”) 到目前为止,代码如下所示:Python中小浮点值的二进制表示,python,floating-point,binary,floating,Python,Floating Point,Binary,Floating,如何将较小的浮点值(如1.942890293094024e-15或2.8665157186802404e-07)转换为Python中的二进制值 但是,我尝试过,它对这么小的值不起作用(我得到以下错误:ValueError:invalid literal for int(),以10为基数:“1.942890293094024e-15”) 到目前为止,代码如下所示: def float_bin(number, places = 3): # split() seperates whole
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
我看到的一个问题是
str(number).split(“.”)的问题。在此之前,我添加了一个简单的hack:number=“{:30f}”。格式化(number)
,这样数字中就没有e
。不过,我不确定结果是否正确。经过一些咨询,我找到了一个解决我问题的好方法。我只需要对它进行一些小的调整(使它成为一个函数,删除自动输入请求等)
非常感谢@kartoon 什么不起作用?你能复制粘贴代码(最小工作示例)和错误消息吗?我得到这个错误:ValueError:invalid literal for int(),以10为基数:“1.942890293094024e-15”。我把代码放到问题上。看看这个。你可能需要执行一些调整。我调整了你发送的代码,它工作了!多谢各位@卡图恩戈德的工作!如果你发布自己问题的答案来帮助需要帮助的人,那将是令人惊讶的。当我这样做时,我看到1.942890293094024e-15(数字)为0.000000:(对我来说似乎是合理的。2e-15非常接近于0。但是,我无法进行近似。我需要一个二进制表达式,而不是0。此外,将此代码段添加到代码中时,我会遇到以下错误:ValueError:没有足够的值来解包(预期为2,得到1),很可能decimal\u converter()
返回int而不是float。请更好地描述您当前的问题。