Python 中小浮点值的二进制表示
Binary representation of small float values in Python
如何将 1.942890293094024e-15 或 2.8665157186802404e-07 等小浮点值转换为 [=25] 中的二进制值=]?
我尝试了 GeeksforGeek's solution,但是,它不适用于这么小的值(我收到此错误:ValueError:以 10 为底的 int() 的无效文字:'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
我看到的一个问题是 str(number).split(".")
。在此之前我添加了一个简单的技巧:number = "{:30f}".format(number)
这样就没有 e
的数字了。不过,我不确定结果是否正确。
经过一番咨询,我发现一个很好的piece of code解决了我的问题。我只需要对其进行一些小调整(使其成为一个函数,删除自动输入请求等)。
非常感谢@kartoon!
如何将 1.942890293094024e-15 或 2.8665157186802404e-07 等小浮点值转换为 [=25] 中的二进制值=]?
我尝试了 GeeksforGeek's solution,但是,它不适用于这么小的值(我收到此错误:ValueError:以 10 为底的 int() 的无效文字:'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
我看到的一个问题是 str(number).split(".")
。在此之前我添加了一个简单的技巧:number = "{:30f}".format(number)
这样就没有 e
的数字了。不过,我不确定结果是否正确。
经过一番咨询,我发现一个很好的piece of code解决了我的问题。我只需要对其进行一些小调整(使其成为一个函数,删除自动输入请求等)。
非常感谢@kartoon!