小编典典

一次生成一个数字的代码

algorithm

我正在尝试制作一个恒定的随机数生成器(我的意思是RNG输出一系列不会重复的数字,但是每次从头开始时都保持不变)。我有一个要打皮。我需要一种算法来逐位生成e位数,最好以Python迭代器或生成器的形式输入到RNG中。我也欢迎生成其他非理性数字的代码。提前致谢。


阅读 328

收藏
2020-07-28

共1个答案

小编典典

是! 我做到了继续分数!

我从生成2的平方根的数字中找到了这些代码

def z(contfrac, a=1, b=0, c=0, d=1):
    for x in contfrac:
        while a > 0 and b > 0 and c > 0 and d > 0:
            t = a // c
            t2 = b // d
            if not t == t2:
                break
            yield t
            a = (10 * (a - c*t))
            b = (10 * (b - d*t))
            # continue with same fraction, don't pull new x
        a, b = x*a+b, a
        c, d = x*c+d, c
    for digit in rdigits(a, c):
        yield digit

def rdigits(p, q):
    while p > 0:
        if p > q:
           d = p // q
           p = p - q * d
        else:
           d = (10 * p) // q
           p = 10 * p - q * d
        yield d

我制作了连续分数生成器:

def e_cf_expansion():
    yield 1
    k = 0
    while True:
        yield k
        k += 2
        yield 1
        yield 1

并将它们放在一起:

def e_dec():
    return z(e_cf_expansion())

然后:

>>> gen = e_dec()
>>> e = [str(gen.next()) for i in xrange(1000)]
>>> e.insert(1, '.')
>>> print ''.join(e)
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035

奖励:生成sqrt(n)的连续分数的代码,其中n是一个正整数,而sqrt(n)是不合理的:

def sqrt_cf_expansion(S):
    """Generalized generator to compute continued
       fraction representation of sqrt(S)"""
    m = 0
    d = 1
    a = int(math.sqrt(S))
    a0 = a
    while True:
        yield a
        m = d*a-m
        d = (S-m**2)//d
        a = (a0+m)//d
2020-07-28