-2
def y(x):

    if x <0:
        return np.cos(x)
    else:
        np.exp(-x)

x = np.arange(-2*np.pi,2*np.pi,0.1)      
plt.plot(x,y(x))
plt.show()

This function supposed to plot y (x) as cos (x) if the x value is less than zero, otherwise exp (-x).

I wrote the code, but it gave me an error. How I can fix the error?

I get this error

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()
gboffi
  • 22,939
  • 8
  • 54
  • 85
Fahad
  • 29
  • 4

1 Answers1

1

There are better ways to do this if performance is an issue, but one solution is to serialize your function to apply it to the whole array

def y(x):
    if x <0:
        return np.cos(x)
    else:
        return np.exp(-x)

vfunc = np.vectorize(y)
x = np.arange(-2*np.pi,2*np.pi,0.1)      
plt.plot(x,vfunc(x))
plt.show()

Probably better in terms of performance:

def y(x):
    return np.concatenate((np.cos(x[x<0]), np.exp(-x[x>=0])))

x = np.arange(-2*np.pi,2*np.pi,0.1)      
plt.plot(x,y(x))
plt.show()
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75