Python math.sin()方法

Pythonmath.sin() 方法是以弧度计算一个数字的正弦的有效方法。输入参数的单位必须是弧度。

Pythonmath.sin() 方法的语法

math.sin(x)

参数

x 要操作的任何正或负弧度值。

返回值

该方法返回一个从-1到1的浮点数,代表x 的正弦,单位是弧度。

例1:在Python中使用math.sin() 方法

import math
x=1.654
value=math.sin(x)
print(f"The sine of {x} is {value}.")
x=0
value=math.sin(x)
print(f"The sine of {x} is {value}.")
x=-34.5
value=math.sin(x)
print(f"The sine of {x} is {value}.")
x=math.pi
value=math.sin(x)
print(f"The sine of {x} is {value}.")

输出:

The sine of 1.654 is 0.996540570833053.
The sine of 0 is 0.0.
The sine of -34.5 is -0.057487478104924564.
The sine of 3.141592653589793 is 1.2246467991473532e-16.

注意,参数可以是整数或浮点数。值可以是正的,也可以是负的。

例 2: 使用math.sin() 方法获取度数的正弦值

import math
print("The sine of 30 degrees is ", math.sin(math.radians(30)))

输出:

The sine of 30 degrees is  0.49999999999999994

我们在与几何学有关的数学计算中使用这些方法,在天文计算中也有一定的应用。

例3:使用math.sin() 方法时的错误

import math
x=math.inf
value=math.sin(x)
print(f"The sine of {x} is {value}.")
x='h'
value=math.sin(x)
print(f"The sine of {x} is {value}.")

输出:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    value=math.sin(x)
ValueError: math domain error
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    value=math.sin(x)
TypeError: must be real number, not str

注意,如果参数值不是一个数字,可能会出现TypeError 异常。