如何解决如何循环此代码?请帮我
当 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。