续部分Python

时间:2016-03-18 06:43:31

标签: python python-3.x approximation continued-fractions

我是Python的新手,并被要求创建一个程序,将输入作为非负整数n,然后计算近似值 使用连续分数的前n + 1项的e值:

我试图破译这个问题,但不能完全理解它所要求的一切。我不是在寻找一个确切的答案,但希望是一个帮助我的例子。

This is the exact question
下面是我之前对连续分数所做的代码。

import math
# Get x from user
x = float(input("Enter x = "))

# Calculate initial variables and print
a0 = x//1
r0 = x-a0
print("a0 =", a0, "\tr0 =", r0)

# Calculate ai and ri for i = 1,2,3 and print results

a1 = 1/r0//1
r1 = 1/r0 - a1
print("a1 =", a1, "\tr1 =", r1)

a2 = 1/r1//1
r2 = 1/r1 - a2
print("a2 =", a2, "\tr2 =", r2)

a3 = 1/r2//1
r3 = 1/r2 - a3
print("a3 =", a3, "\tr3 =", r3)

2 个答案:

答案 0 :(得分:5)

如果没有进一步的信息,使用 e 简单继续分数扩展可能是一个好主意™,如Wikipedia所示:

  

e = [2; 1,2,1,1,4,1,1,6,1,1,8,1,1,10,1,1,12,1,1,   ...]

使用简单的列表推导可以轻松创建此序列。

要评估简单的连续分数扩展,我们需要按相反的顺序处理列表。

以下代码适用于Python 2或Python 3。

#!/usr/bin/env python

''' Calculate e using its simple continued fraction expansion

    See http://stackoverflow.com/q/36077810/4014959

    Also see
    https://en.wikipedia.org/wiki/Continued_fraction#Regular_patterns_in_continued_fractions

    Written by PM 2Ring 2016.03.18
'''

from __future__ import print_function, division
import sys

def contfrac_to_frac(seq):
    ''' Convert the simple continued fraction in `seq` 
        into a fraction, num / den
    '''
    num, den = 1, 0
    for u in reversed(seq):
        num, den = den + num*u, num
    return num, den

def e_cont_frac(n):
    ''' Build `n` terms of the simple continued fraction expansion of e
        `n` must be a positive integer
    '''
    seq = [2 * (i+1) // 3 if i%3 == 2 else 1 for i in range(n)]
    seq[0] += 1
    return seq

def main():
    # Get the the number of terms, less one
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 11
    if n < 0:
        print('Argument must be >= 0')
        exit()

    n += 1
    seq = e_cont_frac(n)
    num, den = contfrac_to_frac(seq)

    print('Terms =', n)
    print('Continued fraction:', seq)
    print('Fraction: {0} / {1}'.format(num, den))
    print('Float {0:0.15f}'.format(num / den))

if __name__ == '__main__':
    main()

<强>输出

Terms = 12
Continued fraction: [2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]
Fraction: 23225 / 8544
Float 2.718281835205993

将程序的参数传递给20以使用Python浮点数获得最佳逼近:2.718281828459045

答案 1 :(得分:2)

值e可以表示为以下连续分数的极限:

  

e = 2 + 1 /(1 + 1 /(2 + 2 /(3 + 3 /(4 + 4 /(...)))))

初始2 + 1 /落在主模式之外,但之后它会继续如图所示。你的工作是在n深度进行评估,此时你停下来并将值返回到那一点。

确保以浮点执行计算。