常数e

时间:2018-08-18 09:23:15

标签: python exponential continued-fractions

我对python非常陌生。我最近刚开始做计算机科学。但是,我在输入数字后如何获得e常量的连续分数的值上一直处于这个话题。请不要为我解决它,而是教我如何解决它。我不确定我应该使用while循环还是for循环,即使我这样做,也不确定如何进行。

这是完整的措辞

This is the question.

2 个答案:

答案 0 :(得分:0)

在解决这些数学问题时,我使用的最佳策略是尝试将问题分解为小步骤。这就是n = 1,2,3的函数。

n = 1
c = 1/2
c = 1/(1+c)
print(2+c)

n = 2
c = 2/3
c = 1/(2+c)
c = 1/(1+c)
print(2+c)

n = 3
c = 3/4
c = 2/(3+c)
c = 1/(2+c)
c = 1/(1+c)
print(2+c)

然后,我将尝试手动计算n = 4和n = 5的功能。一旦掌握了它,就用您自己的话概括一下。然后,将其转换为您选择的编程语言。

答案 1 :(得分:0)

一个人可以在python2中使用以下代码。

# exp(1) from the generalized continued fraction
def expOneFromContinuedFraction( n=30 ):
    """Compute an approximative value of exp(1) from
    e ~ 2 + 1/( 1+1/ (2+2/ (3+3/ ( ... n+n/(n+1) ) ) ) )
    """

    a = 1. + n
    for k in range(n, 0, -1):
        a = k + k/a
    return 2+1/a

for n in range(1,11):
    print "n = %2s :: approximation is %.24f" % ( n, expOneFromContinuedFraction(n) )

复制并粘贴到ipython解释器中给了我

n =  1 :: approximation is 2.666666666666666518636930
n =  2 :: approximation is 2.727272727272727514957751
n =  3 :: approximation is 2.716981132075471538911415
n =  4 :: approximation is 2.718446601941747697850360
n =  5 :: approximation is 2.718263331760264023273521
n =  6 :: approximation is 2.718283693893449814993346
n =  7 :: approximation is 2.718281657666403727802162
n =  8 :: approximation is 2.718281842777827250756673
n =  9 :: approximation is 2.718281827351874291309741
n = 10 :: approximation is 2.718281828538485989099627

我希望弄清楚python失去精度的地方。

请注意,您还可以执行精确的计算,例如通过使用分数支持包。在这种情况下,我使用sage代替python。语言相同,但有更多的“电池”。代码的类似版本,我们不以 float a = 1. + n开头,而是以 sage开头 整数 a = 1+n给出分数。这是精确的计算,使用后验数值。

def sageExpOneFromContinuedFraction( n=30 ):
    a = n+1
    for k in range(n, 0, -1):
        a = k + k/a
    return 2 + 1/a

for n in range(1,11):
    a = sageExpOneFromContinuedFraction(n)
    print "n = %2s :: exp(1) ~ %s ~ %s" % ( n, a, a.n(digits=50) )

结果更好地反映了有理数的十进制表示形式的周期性...

n =  1 :: exp(1) ~ 8/3 ~ 2.6666666666666666666666666666666666666666666666667
n =  2 :: exp(1) ~ 30/11 ~ 2.7272727272727272727272727272727272727272727272727
n =  3 :: exp(1) ~ 144/53 ~ 2.7169811320754716981132075471698113207547169811321
n =  4 :: exp(1) ~ 280/103 ~ 2.7184466019417475728155339805825242718446601941748
n =  5 :: exp(1) ~ 5760/2119 ~ 2.7182633317602642756016989145823501651722510618216
n =  6 :: exp(1) ~ 45360/16687 ~ 2.7182836938934499910109666207227182836938934499910
n =  7 :: exp(1) ~ 44800/16481 ~ 2.7182816576664037376372792913051392512590255445665
n =  8 :: exp(1) ~ 3991680/1468457 ~ 2.7182818427778273384920361985403726496587915070036
n =  9 :: exp(1) ~ 43545600/16019531 ~ 2.7182818273518744088075986743931517096224602330742
n = 10 :: exp(1) ~ 172972800/63633137 ~ 2.7182818285384861664135778815996451660083959085657

注意:请在下次显示自己的计算努力