Tom*_*ace 7 python binary fractions
让我们假设我们有一个代表二进制分数的字符串,例如:
".1"
Run Code Online (Sandbox Code Playgroud)
作为十进制数,这是0.5.Python中是否有一种标准方法可以将这些字符串转换为数字类型(无论是二进制还是十进制都不是非常重要).
对于整数,解决方案很简单:
int("101", 2)
>>>5
Run Code Online (Sandbox Code Playgroud)
int()接受一个可选的第二个参数来提供基数,但float()没有.
我正在寻找功能相同(我认为)的东西:
def frac_bin_str_to_float(num):
"""Assuming num to be a string representing
the fractional part of a binary number with
no integer part, return num as a float."""
result = 0
ex = 2.0
for c in num:
if c == '1':
result += 1/ex
ex *= 2
return result
Run Code Online (Sandbox Code Playgroud)
我认为这样做我想要的,虽然我可能错过了一些边缘案例.
是否有内置或标准的方法在Python中执行此操作?
以下是表达相同算法的较短方式:
def parse_bin(s):
return int(s[1:], 2) / 2.**(len(s) - 1)
Run Code Online (Sandbox Code Playgroud)
它假定字符串以点开头.如果你想要更通用的东西,下面将处理整数和小数部分:
def parse_bin(s):
t = s.split('.')
return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])
Run Code Online (Sandbox Code Playgroud)
例如:
In [56]: parse_bin('10.11')
Out[56]: 2.75
Run Code Online (Sandbox Code Playgroud)