如何在不近似的情况下将循环二进制数转换为十进制数,反之亦然?

问题描述 投票:0回答:1

我想将像 10.1(010) 这样的数字(我将其存储为三元组

('10','1','010')
)转换为十进制,得到 2.6(428571)(或
('2','6','42857')
)。

我想得到精确的数字,重复小数等等,不是一个近似它的浮点数。

我可以轻松地将其转换为浮点数,只需将每个项目读取为整数并将其乘以适当的位值即可:

bin_to_decimal(

('10','1','010')
) = 2 + 1 * 2-1 + 2 * 2-1/(23-1) = 2.642857142857143

我用python写的

def read_numeral(self, numeral, base=2) -> float:
    if ',' not in numeral: numeral = numeral.replace('r',',r')

    integer, finite, period = numeral
    offset = len(finite)

    n = read_int(integer, base)
    if finite: n += read_int(finite, base) * (base ** -offset)
    if period: n += read_int(period, base) * base ** -offset / (base**len(period)-1)

    return n

不过,我无法找到一种方法来获得精确的十进制表示形式。

python binary numbers radix
1个回答
0
投票

请澄清“精确的十进制表示法”的含义。我确信您知道许多可能的输入不能用有限的十进制字符串表示。唉,Python 不支持无限字符串;-)

如果您想要获得多少个十进制数字,则可以轻松使用

decimal
模块,并配置为使用与您有RAM来存储它们一样多的数字。

>>> import decimal
>>> from decimal import Decimal as D
>>> decimal.getcontext().prec = 200  # use 200 digits
>>> D2 = D(2)
>>> result = D2 + 1 * D2**-1 + D2 * D2**-1 / (D2**3 - 1)
>>> result
Decimal('2.6428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571')

顺便说一句,虽然 Python 不支持无限字符串,但无界序列却是另一回事。例如,您可以编写一个生成器来一次生成一个十进制数字。

© www.soinside.com 2019 - 2024. All rights reserved.