0

I am trying to plot a function f. Under is the code that I have.

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    if -np.pi < x < np.pi/2:
        return 0
    elif np.pi/2 < x < np.pi:
        return 1
    else:
        print("Error")

x = np.linspace(-np.pi, np.pi, 1000)

plt.plot(x, f(x))
plt.show()

Could someone help me explain why I get the error message "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()", and how do I fix it?

Have been trying to look on the internet for a solution to my error message, but I do not understand how to solve it.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
  • 1
    `x` has 1000 items. What should `if -np.pi < x` mean? – Michael Butscher Feb 27 '23 at 10:44
  • I am trying to plot a periodic function with a periode 2pi where on interval (-pi, pi) the function f(x) = 0, if -pi < x < pi/2 or f(x) = 1, if pi/2 < x < pi – Daniel Tran Feb 27 '23 at 10:51
  • 1
    "Have been trying to look on the internet for a solution to my error message, but I do not understand how to solve it." To be clear, you tried copying and pasting the error message into a search engine, and you found the linked duplicate, right? Then what, exactly? – Karl Knechtel Feb 27 '23 at 10:51
  • You did not understand @MichaelButscher's question. Let us say that `x` is an array with two elements, like `[-10, 0]`, **What do you think the result should be** when we try `-np.pi < x`? Why? – Karl Knechtel Feb 27 '23 at 10:52
  • Please especially see my answer on the linked duplicate, especially the section titled "Fixing if statements". – Karl Knechtel Feb 27 '23 at 10:54
  • Think about the thing @DanielTran is trying to say. We can compare 10 with 0, but what is meant by comparing a list [10,10] with 0? What should be the answer? To help you out with your error, Try using maps for this. Replacing the plot line by plt.plot(x, list(map(f, x))) should work. – Mathpdegeek497 Feb 27 '23 at 10:55

1 Answers1

0

You might be looking for something like:

plt.plot(x, [f(v) for v in x])

You need to pass each single element to the function rather than the whole array, otherwise the comparison with a number isn't meaningful.