【Python数列、数列和问题】

1.e的计算可用如下表达式展开,试计算e,精确到小数点后6位小数

代码

s = 0
item = 1
jc = 1
n = 0
while abs(item) > 1e-6:
    s = s + item
    n = n + 1
    jc = jc * n
    item = 1/jc
print("{:.6f}".format(s))

输出结果:

2.718282

2.求π的近似值,精确到小数点后6位小数

s = 0
item = 1
flag = 1
n = 0
while abs(item) > 1e-6:
    s = s + item
    flag = -flag
    n = n + 1
    item = flag/(2*n+1)
print("{:.6f}".format(s*4))

输出结果

3.141591

3.求sinx的近似值,精确到小数点后6位小数

import math


s = 0
x = eval(input())
item = x
flag = 1
n = 0
while abs(item) > 1e-6:
    s = s + item
    flag = -flag
    n = n + 1
    item = flag*math.pow(x, 2*n+1)/math.factorial(2*n+1)
print("{:.6f}".format(s))

4.求斐波那契数列的第n项:1,1,2,3,5,8,……

从第三项开始,每一项等于前面两项的和

代码

n = eval(input())
a = b = 1
i = 2
if n <= 2:
    print(a)
else:
    while i <= n:
        item = a+b
        a = b
        b = item
        i += 1
    print(a)

5.求佩尔数列的第n项。佩尔数列是一个整数数列。它的第一项为0,第二项为1,第3项是第2项的2倍再加上第1项,第4项是第3项的2倍再加上第2项,……。最初几个佩尔数是:0,1,2,5,12,29,70,169, 408, 985, 2378……

代码

n = eval(input())
a, b = 0, 1
i = 2
if n == 1:
    print(a)
elif n == 2:
    print(b)
else:
    while i <= n:
        item = a+2*b
        a = b
        b = item
        i += 1
    print(a)

持续更新~~~

你可能感兴趣的:(Python,python)