I always feel that I understand drawing, but every time I encounter complex values, I feel that the idea is not very clear. For example, if we want to make a function numpy.exp(1j * x)
image, we can see that when we bring in the x
value , we will get the complex value. Numerical value. If we use the complex value to draw directly, we will encounter a warning message, the code is as follows:
import numpy as np
import matplotlib.pyplot as plt
vertex = np.pi
x = np.linspace(-vertex, vertex, 100)
f = np.exp(1j * x)
plt.figure()
plt.plot(x, f)
plt.show()
"""
ComplexWarning: Casting complex values to real discards the imaginary part
return array(a, dtype, copy=False, order=order)
"""
We can see the prompt message saying that because we are using complex numbers, we automatically discard the imaginary part and only keep the real part. In the above code, we can np.real()
eliminate this warning message by adding a function at this time . From here, we can also conclude that the drawing command of the matplotlib module requires that the input parameters should be real numbers .
import numpy as np
import matplotlib.pyplot as plt
vertex = np.pi
x = np.linspace(-vertex, vertex, 100)
f = np.exp(1j * x)
plt.figure()
plt.plot(x, np.real(f))
plt.show()
At this time, we eliminated the warning message and successfully output the following image.
It is not difficult to see that this is actually a cosine function, because we know Euler’s formula:
eix = cos (x) + isin (x) e^{ix}=cos(x) + isin(x)eix=cos(x)+i s i n ( x )
herecos(x)
is the real part andsin(x)
the imaginary part, so when we usenp.real(f)
it,sin(x)
the part thatwe actually removed, thee^{ix}
functionat this timeactually becomescos(x)
. In the end, it is not difficult to see that the image we actually get is alsocos(x)
an image of.
So how can I gete^{ix}
the image of the function, the answer is to usenp.abs(f)
. The code is as follows:
import numpy as np
import matplotlib.pyplot as plt
vertex = np.pi
x = np.linspace(-vertex, vertex, 100)
f = np.exp(1j * x)
plt.figure()
plt.plot(x, np.abs(f))
plt.show()
You can see that the final result we obtained is 1
a straight line with constant behavior. This is easy to understand. The e^{ix}
image is actually a unit circle, so its length, that is, the value is always equal 1
. From this we can conclude that when drawing, if the image input parameter value is a complex number, we want to get the original function image, we should use the np.abs()
function to process the image input parameter value instead of using the np.real()
function.
If you still have problems with plurals, you can continue to view this python plural basics (hyperlink, click to jump).
The code word is not easy, if you find it useful, please raise your hand to give a like and let me recommend it for more people to see~