I'm trying to plot a function whose output f(x) depends on floor(x)%3. However, when I tried plotting it using matplotlib, I got this error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I understand that it's because x is an array and so floor(x)%3 doesn't really mean anything. However, is there a way to make python treat x like a single number and not an array?
Here is the code:
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def f(x):
if np.floor(x / 3) % 3 == 1:
return -x + 2 + 4 * np.floor(x/3)
elif np.floor(x / 3) % 3 == 2:
return x - 2 * np.floor((x + 1) / 3)
elif np.floor(x / 3) % 3 == 0:
return x - 2 * np.floor(x / 3)
x = np.linspace(-10, 10, 100)
plt.plot(x, f(x), color='blue')
plt.show()
Any help will be appreciated, thanks in advance!
ifandelif. Instead, you neednp.whereto create conditions for an array expression. In your case, onenp.whereinside the firstnp.whereis needed as you have more than one condition.np.where?def f(x): return np.where(np.floor(x / 3) % 3 == 1, -x + 2 + 4 * np.floor(x/3), np.where(np.floor(x / 3) % 3 == 2, x - 2 * np.floor((x + 1) / 3), x - 2 * np.floor(x / 3))). Note that the normal plot function will join all the points with straight lines, but that your function has gaps. You can useplt.scatter(x, f(x), color='blue')to better visualize this non-continous function.f(8)is2, whilef(7.999)is3.999. Maybe you wantx - 2 * np.floor((x) / 3) - 2for the case when the modulo is 2?