NumPy sin()

sin() 函数计算数组的逐元素正弦值。

正弦是三角函数,它计算直角三角形中与角度相对的边的长度与斜边长度的比率。

示例

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# compute the sine of each angle sine_values = np.sin(angles)
# print resulting sine values print(sine_values) # Output: [0. 0.5 0.70710678 0.8660254 1. ]

sin() 语法

sin() 的语法是

numpy.sin(array, out=None, dtype=None)

sin() 参数

sin() 函数接受以下参数

  • array - 输入数组
  • out (可选) - 用于存储结果的输出数组
  • dtype (可选) - 输出数组的数据类型

sin() 返回值

sin() 函数返回一个包含输入数组逐元素正弦值的数组。


示例 1:计算角度的正弦值

import numpy as np

# array of angles in radians
angles = np.array([0, 1, 2])
print("Angles:", angles)

# compute the sine of the angles sine_values = np.sin(angles)
print("Sine values:", sine_values)

输出

Angles: [0 1 2]
Sine values: [0.         0.84147098     0.90929743]

在上面的示例中,sin() 函数计算了 angles 数组中每个元素的正弦值。

结果值以弧度为单位。


示例 2:使用 out 将结果存储在所需位置

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# create an empty array to store the result
result = np.empty_like(angles)

# compute the sine of angles and store the result in the 'result' array np.sin(angles, out=result)
print("Result:", result)

输出

Result: [0.         0.5        0.70710678 0.8660254  1.        ]

在这里,我们使用了带有 out 参数的 sin() 来计算 angles 数组的正弦值,并将结果直接存储在 result 数组中。

结果的 result 数组包含计算出的正弦值。


示例 3:sin() 中 dtype 参数的使用

import numpy as np

# create an array of angles in radians
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])

# compute the sine of angles with different data types sin_float64 = np.sin(angles, dtype=np.float64) sin_float32 = np.sin(angles, dtype=np.float32)
# print the resulting arrays print("Sine values (float64):", sin_float64) print("Sine values (float32):", sin_float32)

输出

Sine values (float64): [0.         0.5        0.70710678 0.8660254  1.        ]
Sine values (float32): [0.         0.5        0.70710677 0.86602545 1.        ]

在上面的示例中,我们有一个 angles 数组,其中包含以弧度为单位的五个角度。

在这里,我们使用了带有 dtype 参数的 sin() 来以不同的数据类型计算角度的正弦值。

注意sin() 函数通常返回浮点值,因为对于大多数输入,正弦函数会产生非整数值。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战