Python math.sin() 方法



Python math.sin() 方法用于计算弧度制角度的正弦值。从数学上讲,正弦函数定义为直角三角形中给定角的对边与斜边(三角形最长边)的比值。

最常用的正弦值是 0、30、45、60 和 90 度角的正弦值。正弦函数获取的值介于 -1 到 1 之间。当我们将浮点数以外的任何值作为参数传递给它时,此方法会引发 TypeError。

注意 - 此函数无法直接访问,因此我们需要导入 math 模块,然后需要使用 math 静态对象调用此函数。

语法

以下是 Python math.sin() 方法的语法:

math.sin(x)

参数

  • x - 这必须是一个数值。

返回值

此方法返回一个介于 -1 和 1 之间的数值,表示角度的正弦。

示例

以下示例演示了 Python math.sin() 方法的使用方法。在这里,我们尝试传递标准正弦角,并使用此方法查找它们的三角正弦比。

import math
print ("sin(3) : ",  math.sin(3))
print ("sin(-3) : ",  math.sin(-3))
print ("sin(0) : ",  math.sin(0))
print ("sin(math.pi) : ",  math.sin(math.pi))
print ("sin(math.pi/2) : ",  math.sin(math.pi/2))

运行以上程序时,会产生以下结果:

sin(3) :  0.14112000806
sin(-3) :  -0.14112000806
sin(0) :  0.0
sin(math.pi) :  1.22464679915e-16
sin(math.pi/2) :  1.0

示例

此方法不仅可以用于标准角度,还可以用于查找非标准角度的正弦比。

在此示例中,我们创建了多个数值对象,这些对象以弧度表示非标准角度。为了找到它们的正弦比结果,这些值作为参数传递给此方法。

import math
# If the sine angle is pi
x = 5.48
sine = math.sin(x)
print("The sine value of x is:", sine)
# If the sine angle is pi/2
x = 1.34
sine = math.sin(x)
print("The sine value of x is:", sine)
# If the sine angle is 0
x = 0.78
sine = math.sin(x)
print("The sine value of x is:", sine)

执行以上代码时,我们得到以下输出:

The sine value of x is: -0.7195716728205075
The sine value of x is: 0.9734845416953194
The sine value of x is: 0.7032794192004103

示例

即使复数仍然被认为是数字,此方法也只接受实数作为参数。

让我们来看一下将复数作为参数传递给 sin() 方法的场景。该方法会引发 TypeError 异常。

import math
# If the sine angle is a complex number
x = 12-11j
sine = math.sin(x)
print("The sine value of x is:", sine)

以下是上述代码的输出:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    sine = math.sin(x)
TypeError: must be real number, not complex

示例

我们可以使用 math.radians() 方法将角度从度数转换为弧度,然后将其作为参数传递给 sin() 方法。

在下面的示例中,我们创建了一个数字对象,它保存以度数表示的正弦角。由于 sin() 方法接受以弧度为单位的参数,因此我们可以调用此对象上的 radians() 方法将其转换为相应的弧度值。然后,我们将此弧度值作为参数传递给该方法,并找到其正弦值。

import math
# Take the sine angle in degrees
x = 60
# Convert it into radians using math.radians() function
rad = math.radians(x)
# Find the sine value using sin() method
sine = math.sin(rad)
# Display the sine ratio
print("The sine value of x is:", sine)

上述代码的输出如下:

The sine value of x is: 0.8660254037844386
python_maths.htm
广告
© . All rights reserved.