Taylor Series of cos(x) +1 with Tensorflow

Viewed 152

I am calculating the approximation of the function cos(x) + 1 using a Taylor Series Expansion up to order 7 using Tensorflow.

I wrote the following code:

x=tf.constant(3.14159,dtype=tf.float32)
result = tf.constant(2,dtype=tf.float32)

    if i % 2 == 1:
        num=tf.math.pow(x, i*2)

        den=math.factorial(i*2)

        result=tf.math.subtract(result,tf.math.divide(num,den))

    else:
        num=tf.math.pow(x, i*2)
        

        den=math.factorial(i*2)

        result=tf.math.add(result,tf.math.divide(num,den))

The Taylor Series of the function is

enter image description here

However, when x=3.14, I get conflicting results:

MY CODE       ---> -0.21135163
Actual answer ---> 3.52077e-12

Can anyone help me point out where am I going wrong?

1 Answers

This Taylor Series diverge very quickly. To get a correct result for your input, you need to use a much higher order.

Here is an example:

2 - x**2/2! + x**4/4! - x**6/6!                       ---> -0.2105183783
2 - x**2/2! + x**4/4! - x**6/6! + x**8/8!             --->  0.0238595229
2 - x**2/2! + x**4/4! - x**6/6! + ... - x**10/10!     ---> -0.0018168365
2 - x**2/2! + x**4/4! - x**6/6! + ... + x**12/12!     --->  0.0001010319
2 - x**2/2! + x**4/4! - x**6/6! + ... - x**14/14!     ---> -2.865991e-06
2 - x**2/2! + x**4/4! - x**6/6! + ... + x**16/16!     --->  1.402307e-06

Another problem of this method is that it is not very accurate, even with a high order because it have a high condition number and will likely suffer from floating point accumulation issues. Thus, to put it shortly: don't use this method.

You can find more information about it on Wikipedia.

Related