using a while loop to calculate arctan taylor series in python

192 Views Asked by At

need to estimate arctan and subtract the current value from the last value. I'm very new to python and I have only this so far:

again==1
while again==1:
    x = float(input('enter tangent'))
    tolerance=input('enter reasonable tolerance')
    import math
    n=0
    while estimate-estimate>=tolerance:
        estimate=(-1**n)(x**(n+1))/(2n+1)
        n=n+1
        print(estimate)

    print(math.atan(x))
    difference=estimate-(math.atan(x))
    print(difference)
    again = int(input("do you want to run program again? yes = 1, no =0"))

How do I go about finding the difference between the current arctan value and the last value and how do I output the number of terms used?

1

There are 1 best solutions below

0
Greg Cowell On BEST ANSWER

For tangents between -1 and 1, try:

import math

again = 1
while again == 1:
    current_sum = 0
    previous_sum = 100
    x = float(input("enter tangent: "))
    tolerance = float(input("enter reasonable tolerance: "))
    n = 0
    while math.fabs(current_sum - previous_sum) >= tolerance:
        term = (-1) ** n * (x ** (2 * n + 1)) / (2 * n + 1)
        previous_sum = current_sum
        current_sum += term
        n += 1
    print(
        f"Actual={math.atan(x)}, Estimate={current_sum}, Number of Terms={n}"
    )
    again = int(input("do you want to run program again? yes = 1, no = 0: "))

Please note the use of extra variables and correction of errors in your Taylor Series formula.