pythontypeerrortaylor-series

Typeerror during Taylor-approximation


For Uni I'm doing this assignment where I have to approximate the difference between the sine function and its n-th Taylor approximation. When running the code plotting these two functions I run into the following error:

TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind''

The weird thing (in my opinion) is that the program works fine for n <= 20, but when I choose anything above that, it throws this error.

Does anyone know where in my code the problem may lie? Thanks in advance.

import matplotlib.pyplot as plt
import numpy as np
import math

def constant(n, x):
    return np.full(x.shape, (2*math.pi)**(n+1)/(math.factorial(n+1)))

def taylor_n(n,x):
    val = 0
    for i in range(1, n+1):
        if i%2 == 1:
            val += (-1)**((i-1)/2)* x**i/math.factorial(i)
    return val

N = [1, 5, 10, 20, 50]
x = np.linspace(0,2*math.pi,100)


for n in N:
    plt.plot(x, abs(np.sin(x) - taylor_n(n, x)))
    plt.plot(x, constant(n, x))

Solution

  • Looks like float underflow. If cast to decimal it works:

    import decimal
    
    ...
    
    def taylor_n(n,x):
        val = 0
        for i in range(1, n+1):
            if i%2 == 1:
                val += np.array((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i), dtype=np.dtype(decimal.Decimal))
        return val
    

    Inside taylor_n function expression ((-1) ** ((i - 1) / 2) * x ** i / math.factorial(i)) has type float64, but when i becomes greater the type of expression becomes complex128 and these types can't be summed.

    Problem was only while N=50 (actually, N>20), another values calculated correctly. For N=50 plot is:

    enter image description here