Python-数学模块

时间:2020-02-23 14:42:59  来源:igfitidea点击:

在本教程中,我们将学习Python中的数学模块和数学函数。

数学模块

"math"模块是Python中可用的标准模块,它为开发人员提供数学函数。

要使用数学模块中可用的函数,我们必须首先使用 import声明。

编写以下行以导入数学模块。 import math

数学常数

下面是Python中常用的数学常量。

常数描述
e
pi

在下面的示例中,我们将打印数学常数的值。

# import module
import math
# output
print("e:", math.e)         # e: 2.718281828459045
print("pi:", math.pi)       # pi: 3.141592653589793

数学函数

下面是Python中数学模块的一些常用数学函数。

函数说明
math.ceil(x)返回大于或者等于x的最小整数
math.fabs(x)返回x的绝对值
math.floor(x)返回最大的数字,不大于x
math.log(x)找到x的自然对数(其中,x>0)。
math.log10(x)找到x的基本10对数(其中,x>0)。
max(x1, x2, ...)返回给定值的最大值。
min(x1, x2, ...)返回给定值的最小值。
math.pow(x, y)返回x的y的幂示例:xy
round(x, [,n])返回x到n个小数点的舍入值。
math.sqrt(x)返回x的平方根

在下面的Python程序中,我们使用了一些数学函数。

# import module
import math
# output
print("ceil:", math.ceil(3.14))              # ceil: 4
print("fabs:", math.fabs(3.14))              # fabs: 3.14
print("fabs:", math.fabs(-3.14))             # fabs: 3.14
print("floor:", math.floor(-3.14))           # fabs: -4
print("log:", math.log(8))                   # log: 2.0794415416798357
print("log10:", math.log10(8))               # log10: 0.9030899869919435
print("max:", max(1, 5, 3, 4))               # max: 5
print("min:", min(9, 3, 1, 6))               # min: 1
print("pow:", math.pow(2, 10))               # pow: 1024
print("round:", round(3.14159))              # round: 3
print("round:", round(3.14159, 2))           # round: 3.14
print("sqrt:", math.sqrt(4))                 # sqrt: 2

数学三角函数

下面是Python数学模块中一些常用的三角函数。

函数描述
math.acos(x)
math.asin(x)
math.atan(x)
math.cos(x)
math.sin(x)
math.tan(x)
math.degrees(x)
math.radians(x)

在下面的Python程序中,我们使用了一些三角函数。

# import module
import math
# output
print("acos:", math.acos(0.5))              # acos: 1.0471975511965976
print("asin:", math.asin(0.5))              # asin: 0.5235987755982988
print("atan:", math.atan(0.5))              # atan: 0.46364760900080615
print("cos:", math.cos(1.047197551))        # cos: 0.5000000001702587
print("sin:", math.sin(0.523598775))        # sin: 0.49999999948185797
print("tan:", math.tan(0.463647609))        # tan: 0.4999999999989924
print("degree:", math.degrees(3.1415926))   # degree: 179.99999692953102
print("radian:", math.radians(180))         # radian: 0.4999999999989924