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?
Any help would be greatly appreciated!
CodePudding user response:
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()
CodePudding user response:
If you are new to programming, this may appear a little different from you are doing right now, however I have essentially split the functions up to explain what each component does and, more importantly, used numpy's built-in functions which will prove to be more efficient than nested loops, especially as your data becomes larger.
To understand what's happening with the function f
, look-up (list) comprehensions in Python, but it's basically a for
loop expressed in a single line.
In [24]: import numpy as np
...: import matplotlib.pyplot as plt
In [25]: def summand(n, x):
...: """ Return an array of `x`'s size for a given value of `n`.
...: Each element of the array is a value of the function computed
...: at a value in `x` with the given `n`.
...: """
...: return (2 / (n * np.pi)) * (np.cos(n * np.pi / 2) - 1) * np.sin(n * x / 2)
...:
In [26]: def f(x, N=5):
...: """ Return the sum of the summands computed for
...: values of `n` ranging from 1 to N 1 with a given array `x`
...: """
...: return sum(summand(n, x) for n in range(1, N 1))
...:
In [27]: x = np.linspace(-2*np.pi, 6*np.pi, 500)
In [28]: plt.plot(x, f(x))
Out[28]: [<matplotlib.lines.Line2D at 0x23e60b52a00>]
In [29]: plt.show()