簡體   English   中英

如何在python中將浮點數轉換為基數3

[英]How to convert floating point number to base 3 in python

如何將 Python 中的基數為 10 的浮點數轉換為基數為 N 的浮點數?

特別是在我的情況下,我想將數字轉換為基數 3(獲得基數為 3 的浮點數的表示),以使用Cantor set進行計算。

經過一番擺弄,這就是我想出的。 我謹記伊格納西奧的警告,謙虛地呈現給你。 如果您發現任何缺陷,請告訴我。 除其他事項外,我沒有理由相信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

這些是返回整數的迭代器。 如果您需要字符串轉換,請告訴我; 但我想你能應付得了。

編輯:實際上再看看這個,似乎if x == 0: breakbase3fractionyield之后base3fraction給了你幾乎任意的精度。 我繼續補充說。 盡管如此,我還是要離開precision論點; 能夠限制該數量是有意義的。

另外,如果你想轉換回十進制分數,這就是我用來測試上面的。

sum(d * (3 ** (-i - 1)) for i, d in enumerate(base3fraction(x)))

更新

出於某種原因,我受到了這個問題的啟發。 這是一個更通用的解決方案。 這將返回兩個生成器,它們生成表示任意基數中給定數字的整數部分和小數部分的整數序列。 請注意,這僅返回兩個生成器來區分數字的部分; 在這兩種情況下,生成數字的算法是相同的。

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)

雖然已經過去了 8 年,但我認為還是值得提一個更緊湊的解決方案。

def baseConversion( x=1, base=3, decimals=2 ):
    import math
    n_digits = math.floor(-math.log(x, base))#-no. of digits in front of decimal point
    x_newBase = 0#initialize
    for i in range( n_digits, decimals+1 ):
        x_newBase = x_newBase + int(x*base**i) % base * 10**(-i)
    return x_newBase

例如調用函數來轉換數字 5+1/9+1/27

def baseConversion( x=5+1/9+1/27, base=3, decimals=2 ) 
12.01
def baseConversion( x=5+1/9+1/27, base=3, decimals=3 ) 
12.011

您可以嘗試使用此解決方案將浮點字符串轉換為給定的基數。

def eval_strint(s, base=2):
    assert type(s) is str
    assert 2 <= base <= 36
    ###
    ### YOUR CODE HERE
    ###
    return int(s,base)

def is_valid_strfrac(s, base=2):
    return all([is_valid_strdigit(c, base) for c in s if c != '.']) \
        and (len([c for c in s if c == '.']) <= 1)
    
def eval_strfrac(s, base=2):
assert is_valid_strfrac(s, base), "'{}' contains invalid digits for a base-{} number.".format(s, base)

stg = s.split(".")
float_point=0.0
if len(stg) > 1:
    float_point = (eval_strint(stg[1],base) * (base**(-len(stg[1]))))
stg_float = eval_strint(stg[0],base) + float_point
return stg_float

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM