How can I get the plot of the function, y = x**(3/5)*(4-x)
?
I used this code:
import matplotlib.pyplot as plt
import numpy as np
# def pow35(x):
# if x >= 0:
# return x**0.6
# elif x < 0:
# return -(-x)**0.6
x = np.linspace(-5,5,100)
# y = pow35(x)*(4-x)
y = x**(3/5)*(4-x)
plt.plot(x,y)
plt.show()
but it only plots from 0 to 5, the negative part is ignored.
I also tried to use a customized function like pow35()
, but it outputs this error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in pow35
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
CodePudding user response:
It's because when x<0, x**(3/5)*(4-x) will have an imaginary part.
You can take a look a this if you want to plot complex numbers.
Using your custom function should work however. It just isn't exactly the same as x**(3/5) because it basically takes the abs values of x, raises them to 3/5, and adds a minus sign to the values that are negative in the original x. Thus the negative side of the array will end up having the same values as the positive side with just their signs flipped (so a "mirror image" of the x>=0 part). If that is what you want, you'll get there using your own function.
The error you are getting from the function is because x is an array and x>=0 will result in an array with truth values for each element of x of whether they are greater than or equal to zero.
(x>=0).any() will return whether any element of x is greater than or equal to zero and (x>=0).all() will return whether all the elements of x are greater than or equal to zero. To raise the elements where x>=0 to the power of 0.6, you should be able to do x[x>=0] = x[x>=0]**0.6. For the other operation you should be able to do x[x<0] = -(-x[x<0])**0.6.
The function would then become:
def pow35(x):
x[x>=0] = x[x>=0]**0.6
x[x<0] = -(-x[x<0])**0.6
return x