pythonmathplotdegrees

Python: How to convert Radians to Degrees with np.arange() and a function


I am attempting to plot a cosine wave in degrees, from 0 to 360.

x = np.arange(0, 360, 0.1)
y = np.cos(x)

I cant find a clear example of how to the conversion fits with arange() command, or perhaps its the plot command. keeping the x = np.arange(0, 360, 0.1)
I have tried:

y = np.cos(np.rad2deg(x))
y = np.cos(x * 180/np.pi)
y = np.cos(np.degrees(x))

and a multitude of variations. These functions each plot something chaotic and squiggly, but not a basic cos(x).


Solution

  • y = np.cos(np.rad2deg(x))
    y = np.cos(x * 180/np.pi)
    y = np.cos(np.degrees(x))
    

    In all three of these, you are converting radians to degrees. Your x is already in degrees. You need to convert it to radians before applying cos(). So:

    y = np.cos(np.deg2grad(x))
    y = np.cos((x * np.pi)/180)
    y = np.cos(np.radians(x))