Search code examples
pythonpython-3.xfunctionformattaylor-series

Taylor Series - How do I stop the function when T1 == T0?


I am required to make the Taylor Series in python without importing any files like import math nor using any built-in math functions like round().

My code so far for the cosine function is as such below:

x = abs(float(input("Please input the degree: "))) 
rad = x * 3.14159265358979323846264338327950288419716 / 180

def cos():
    f = 1
    i = 0
    c = 0
    T0 = 1
    T1 = 0
    i = 0
    Tp = 1
    prec = 11
    TDif = 1
    print("{0:^45} {1:^13} {2:^47} {3:>12}".format("x", "termOld", "termNew", "tOld - TNew"))

    while T1 != T0:
        T0 = Tp
        T1 = (-1 * T0 * rad * rad) / ((i + 1) * (i + 2))
        Tp = T1
        f += T1
        c += 1
        i += 2
        TDif = abs(T0) - abs(T1)
        print("{:02d} ==> {:^30.11f} {:^30.11f} {:^30.11f} {:^30.11f}".format(c, f, abs(T0), abs(T1), abs(TDif)))

cos()

And here's the output:

Please input the degree: 30
                     x                           termOld                        termNew                      tOld - TNew    
01 ==>         0.86292216110                  1.00000000000                  0.13707783890                  0.86292216110         
02 ==>         0.86605388342                  0.13707783890                  0.00313172232                  0.13394611658         
03 ==>         0.86602526410                  0.00313172232                  0.00002861932                  0.00310310300         
04 ==>         0.86602540421                  0.00002861932                  0.00000014011                  0.00002847921         
05 ==>         0.86602540378                  0.00000014011                  0.00000000043                  0.00000013968         
06 ==>         0.86602540378                  0.00000000043                  0.00000000000                  0.00000000043         
07 ==>         0.86602540378                  0.00000000000                  0.00000000000                  0.00000000000         
08 ==>         0.86602540378                  0.00000000000                  0.00000000000                  0.00000000000         
09 ==>         0.86602540378                  0.00000000000                  0.00000000000                  0.00000000000
...

and the last one repeats until the counter reaches 80.

Now here's my question. How do I stop the function when termOld (T0) == termNew (T1) following the precision they are set at, with the conditions set above? Like, I know T0 is not really == T1 at counter 9 if you look at the entire decimal, but because the precision is at 11, I want to stop it when the strings of just 0's appear as output, i.e. at the counter 07.


Solution

  • Changing while T1 != T0: to while abs(TDif) > .5*10**(-prec): should do the trick. This ensures that the difference will round down to zero at the given decimal precision.