pythonnumpymatplotlibcomplex-numbersreal-number

Plot real part of complex-valued function in Python


I am trying to plot the following function...

f(k) = Re[k - 0.5*(sqrt(1 - 4*k) + 1)]

for k = [-2, 2], but the best I can do is...

import matplotlib.pyplot as plt
import numpy as np
k = np.linspace(-2, 2, 100)
f = np.real(k - 0.5*(np.sqrt(1 - 4*k) + 1))
plt.plot(k, f)
plt.axis([-2,2,-10,10])

which plots fine for k = [-2, 1/4) but nothing for complex results. Can I do this some other way?


Solution

  • you have to tell to np.sqrt that you are using complex number an easy way is to add 0jat the end of the parameter. After you call the real part of your result. You can also use this numpy.lib.scimath.sqrt

    import matplotlib.pyplot as plt
    import numpy as np
    k = np.linspace(-2, 2, 100)
    f = np.array(k - 0.5*(np.sqrt(1 - 4*k+0j) + 1))
    plt.plot(k, f.real)
    plt.axis([-2,2,-10,10])
    plt.show()
    

    I'm getting this plot enter image description here

    With your code I was getting enter image description here