pythonfunctionplottypeerrorlinspace

TypeError: only size-1 arrays can be converted to Python scalars when trying to plot a function


I've got the current code:

from math import cos, sin, pi
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    
    values = []
    s = 0
    for n in range(1, 6, 1):
        s += -((2/(n*pi))*(((cos((n*pi)/2))-1)*(sin((n/2)*x))))
        values.append(s)
        
    return values

x = np.linspace(-2*pi, 6*pi, 500)
plt.plot(f(x))

I'm supposed to plot f(x), but when I run the code, I get this error:

TypeError: only size-1 arrays can be converted to Python scalars

Any ideas as to what I'm doing wrong?


Solution

  • I think the x value in the formula only applies for one value of x, and since you have multiple x in a form of a list, you have to iterate through each of them (for example, using for xval in x:), perform the calculation and append the calculated value to the values list

    from math import cos, sin, pi
    import numpy as np
    import matplotlib.pyplot as plt
    
    def f(x):
        values = []
        for xval in x:
            s = 0
            for n in range(1, 6, 1):
                s += -((2/(n*pi))*(((cos((n*pi)/2))-1)*(sin((n/2)*xval))))
            values.append(s * -1)
            
        return values
    
    x = np.linspace(-2*pi, 6*pi, 500)
    plt.plot(f(x))
    plt.show()