0

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!

5
  • Your problem hasn't anything to do with the modulo operator. The problem is the use of if and elif. Instead, you need np.where to create conditions for an array expression. In your case, one np.where inside the first np.where is needed as you have more than one condition. Commented Jan 1, 2023 at 22:10
  • @JohanC could you please explain how I should use np.where? Commented Jan 1, 2023 at 22:23
  • 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 use plt.scatter(x, f(x), color='blue') to better visualize this non-continous function. Commented Jan 2, 2023 at 0:06
  • @JohanC do you know why the function is non-continuous? I didn't think it'd be the case Commented Jan 2, 2023 at 20:56
  • Well, that's how you defined the function. E.g f(8) is 2, while f(7.999) is 3.999. Maybe you want x - 2 * np.floor((x) / 3) - 2 for the case when the modulo is 2? Commented Jan 2, 2023 at 21:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.