【问题标题】:Python: How to convert Radians to Degrees with np.arange() and a functionPython:如何使用 np.arange() 和函数将弧度转换为度数
【发布时间】:2020-08-28 14:21:05
【问题描述】:

我正在尝试绘制从 0 到 360 度的余弦波。

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

我找不到一个明确的例子来说明如何转换适合 arange() 命令,或者可能是它的 plot 命令。 保持 x = np.arange(0, 360, 0.1)
我试过了:

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

以及多种变体。这些函数都绘制了一些混乱和曲折的东西,但不是基本的 cos(x)。

【问题讨论】:

    标签: python math plot degrees


    【解决方案1】:
    y = np.cos(np.rad2deg(x))
    y = np.cos(x * 180/np.pi)
    y = np.cos(np.degrees(x))
    

    在所有这三个中,您都将弧度转换为度数。你的 x 已经是度数了。您需要在应用 cos() 之前将其转换为弧度。所以:

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

    【讨论】:

      【解决方案2】:

      由于您的角度 x 以度为单位,因此您希望使用多种方法之一转换为弧度,例如 np.deg2rad

      所以代码是:

      x = np.arange(0, 360, 0.1) # angles in degrees from 0 to 360
      y = np.cos(np.deg2rad(x))  # convert x to degrees before
                                 # applying cosine
      

      More methods

      完整代码(Jupyter 笔记本)

      %matplotlib inline
      import matplotlib.pyplot as plt
      plt.style.use('seaborn-whitegrid')
      import numpy as np
      
      x = np.arange(0, 360, 0.1)
      y = np.cos(np.deg2rad(x))  
      plt.plot(x, y, 'o', color='blue')
      plt.xlabel('Angle (Degrees)')
      plt.ylabel('Cosine')
      

      【讨论】:

        猜你喜欢
        • 2015-11-28
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多