如何循环此代码?请帮我

问题描述

当 n 的值按顺序增加时,n 的值必须写入泰勒级数并按顺序显示和。你能尽快帮忙吗?你能显示适当的循环吗?

import math
x = 1.010
print("My x value is",format(x,".3f"))
math.cos(x)
print("Exact value of cos(x) =",math.cos(x))
math.exp(x)
print("Exact value of e^x =",math.exp(x),"\n")
print("The sum of two =",math.cos(x)+math.exp(x),"\n")
print("If the precision is 3 digits,",format(math.cos(x)+math.exp(x),".3f"))
n=0
num1=x**(2*n)
deno1=math.factorial(2*n)
taylor1= ((-1)**n)*(num1/deno1)
print(taylor1)
n=1
num1=x**(2*n)
deno1=math.factorial(2*n)
taylor2= ((-1)**n)*(num1/deno1)
print(taylor2)
n=2
num1=x**(2*n)
deno1=math.factorial(2*n)
taylor3= ((-1)**n)*(num1/deno1)
print(taylor3)
n=3
num1=x**(2*n)
deno1=math.factorial(2*n)
taylor4= ((-1)**n)*(num1/deno1)
print(taylor4)
sum_taylor=taylor1+taylor2+taylor3+taylor4
print("according to taylor series,cos(x) sum is",sum_taylor)

解决方法

import math
x = 1.010
print("My x value is",format(x,".3f"))
math.cos(x)
print("Exact value of cos(x) =",math.cos(x))
math.exp(x)
print("Exact value of e^x =",math.exp(x),"\n")
print("The sum of two =",math.cos(x)+math.exp(x),"\n")
print("If the precision is 3 digits,",format(math.cos(x)+math.exp(x),".3f"))

i = 3 #Max precision required
sum_taylor = 0
for n in range(i+1):
    num = x**(2*n)
    deno = math.factorial(2*n)
    taylor = ((-1)**n)*(num/deno)
    print(taylor)
    sum_taylor= sum_taylor + taylor
    
print("according to taylor series,cos(x) sum is",sum_taylor)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...