如何在python中将浮点数转换为base 3

Her*_*aaf 7 python

如何将Python中的base-10浮点数转换为base-N浮点数?

特别是在我的情况下,我想将数字转换为基数3(获得基数3中的浮点数的表示),用于使用Cantor集进行计算.

sen*_*rle 7

经过一番摆弄,这就是我想出来的.我谦卑地把它呈现给你,记住伊格纳西奥的警告.如果您发现任何缺陷,请告诉我.除其他事项外,我没有理由相信这个precision论点提供的不仅仅是模糊的保证,即第一个precision数字非常接近正确.

def base3int(x):
    x = int(x)
    exponents = range(int(math.log(x, 3)), -1, -1)
    for e in exponents:
        d = int(x // (3 ** e))
        x -= d * (3 ** e)
        yield d

def base3fraction(x, precision=1000):
    x = x - int(x)
    exponents = range(-1, (-precision - 1) * 2, -1)
    for e in exponents:
        d = int(x // (3 ** e))
        x -= d * (3 ** e)
        yield d
        if x == 0: break
Run Code Online (Sandbox Code Playgroud)

这些是返回int的迭代器.如果你需要字符串转换,请告诉我.但我想你可以解决这个问题.

编辑:实际上看一下这个,看起来像是if x == 0: break一行后yield,base3fraction给你几乎任意的精度.我继续说道.不过,我正在离开这个precision论点; 能够限制数量是有意义的.

此外,如果你想转换回小数部分,这是我用来测试上面的.

sum(d * (3 ** (-i - 1)) for i, d in enumerate(base3fraction(x)))
Run Code Online (Sandbox Code Playgroud)

更新

出于某种原因,我对这个问题感到鼓舞.这是一个更通用的解决方案.这将返回两个生成器,这些生成器生成整数序列,表示任意基数中给定数字的整数和小数部分.注意,这只返回两个生成器来区分数字的各个部分; 在两种情况下,用于生成数字的算法都是相同的.

def convert_base(x, base=3, precision=None):
    length_of_int = int(math.log(x, base))
    iexps = range(length_of_int, -1, -1)
    if precision == None: fexps = itertools.count(-1, -1)
    else: fexps = range(-1, -int(precision + 1), -1)

    def cbgen(x, base, exponents):
        for e in exponents:
            d = int(x // (base ** e))
            x -= d * (base ** e)
            yield d
            if x == 0 and e < 0: break

    return cbgen(int(x), base, iexps), cbgen(x - int(x), base, fexps)
Run Code Online (Sandbox Code Playgroud)