【问题标题】:How can I loop this code ? Please help me我怎样才能循环这段代码?请帮我
【发布时间】:2021-06-11 12:37:40
【问题描述】:

虽然 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)

【问题讨论】:

    标签: loops math sum taylor-series


    【解决方案1】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      相关资源
      最近更新 更多