简体   繁体   中英

Taylor Series Loop for sin(x) in Python

I am working on a Python program in Jupyter Notebook that outputs the sum of a Taylor Series of sin(x) and e^x and compares them to the math module's output for a school assignment. The e^x portion seems to work fine, the output sum is close to the module calculation. However, the sin(x) portion is completely off and I'm not sure why. I'm sure it has to be in my series_sum calculation setup, but I've been staring at it for hours with no luck. Please help if you can, I greatly appreciate it!

import math

def taylor(func,x,terms=10):
    series_sum=0
    if func=='sin':
        for i in range(terms):
            if(i==10):
                break;
            series_sum=series_sum+(math.pow(-1,i)*math.pow(x,2*i+1))/math.factorial(2*i+1)
            math_value=math.sin(x)
        print("The Taylor series approx is",series_sum,"and the math function value is",math_value)
    else:
        for i in range(terms):
            if(i==10):
                break;
            series_sum=series_sum+math.pow(x,i)/math.factorial(i)
            math_value=math.exp(x)
        print("The Taylor series approx is",series_sum,"and the math function value is",math_value)
func=input("Which function to use sin/exp:")
x=int(input("Enter the value of x: "))
terms=int(input("Enter number of terms: "))
if x>50:
    raise Exception("x should NOT exceed 50")
elif x<-50:
    raise Exception("x should NOT be less than -50")
elif terms>100:
    raise Exception("terms should NOT exceed 100")
elif terms<1:
    raise Exception("terms should NOT be less than 1")
else:
    taylor(func,x,terms)

Sinus is defined in the range from 0 to 2*PI so to get more precise result just do x = x % (2 * math.pi) before computing sin Tayloror series:

import math

def sin_taylor(x, terms=10):
    series_sum = 0
    math_value = math.sin(x)
    x = x % (2 * math.pi)
    for i in range(terms):
        series_sum = series_sum + (
            math.pow(-1, i) * math.pow(x, 2 * i + 1) / math.factorial(2 * i + 1)
        )

    print(
        "The Taylor series approx is",
        series_sum,
        "and the math function value is",
        math_value,
    )


sin_taylor(62.3, 10)

Prints:

The Taylor series approx is -0.5072969037125172 and the math function value is -0.5071313157685321

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM