Python【math数学函数】

Python【math数学函数】

数论与表示函数

1.ceil()和floor()

向上向下取整

import math

# math.ceil(x) 返回大于等于x的最小的整数
# math.floor(x) 返回小于等于x的最大的整数
print(math.ceil(3.5))
print(math.ceil(3.0))
print(math.ceil(3))

print(math.floor(4))
print(math.floor(3.5))
print(math.floor(3))

输出:

4
3
3
4
3
3

2.comb()

import math

# math.comb(n,k) 返回组合数Cnk的值
print(math.comb(5,2))
print(math.comb(5,5))
print(math.comb(5,6))

输出:

10
1
0

3.copysign()

import math

# math.copysign(x,y) 返回x的绝对值和y的符号结合起来的数
print(math.copysign(-5,2))
print(math.copysign(5,-5))

输出:

5.0
-5.0

4.fabs()

import math

# math.fabs(x) 返回x的绝对值
print(math.fabs(-3.5))
print(math.fabs(3))

输出:

3.5
3.0

5.factorial()

import math

# math.factorial(x) 返回x阶层
#  如果 x 不是整数或为负数时则将引发ValueError
print(math.factorial(0))
print(math.factorial(4))
print(math.factorial(10))

输出:

1
24
3628800

6.gcd()

import math

# math.gcd(x,y) 返回x、y的最大公约数
print(math.gcd(10,5))
print(math.gcd(11,10))
print(math.gcd(15,10))

输出:

5
1
5

7.lcm()

import math

# math.lcm(x,y) 返回x、y的最小公倍数
print(math.lcm(10,5))
print(math.lcm(11,10))
print(math.lcm(15,10))

输出:

10
110
30

幂函数与对数函数

1.exp()和math.e和pow()

import math

# math.exp(x) 返回自然常数的x次方
# 和使用math.e ** x 或者 pow(math.e,x)的意思一样
# 不过math.exp(x) 通常更精确
print(math.exp(1))
print(math.e ** 1)
print(pow(math.e,1))
print('------------------')
print(math.exp(2))
print(math.e ** 2)
print(pow(math.e,2))
print('------------------')
print(math.exp(10))
print(math.e ** 10)
print(pow(math.e,10))

输出:

2.718281828459045
2.718281828459045
2.718281828459045
------------------
7.38905609893065
7.3890560989306495
7.3890560989306495
------------------
22026.465794806718
22026.465794806703
22026.465794806703

2.log()和log2()和log10()

import math

# math.log(x)返回以e为底,x的对数
print(math.log(math.e ** 2))
# math.log2(x)返回以2为底x的对数
print(math.log2(1024))
# math.log10(x)返回以10为底x的对数
print(math.log10(1000))

输出:

2.0
10.0
3.0

3.sqrt(x)

import math

# math.sqrt(x) 返回x的平方根
print(math.sqrt(10))
print(math.sqrt(16))

输出:

3.1622776601683795
4.0

三角函数

1.asin、acos()、atan()

import math

# math.asin(x) 返回以弧度为单位的x的反正弦值
print(math.asin(1))
# math.acos(x) 返回以弧度为单位的x的反余弦值
print(math.acos(-1))
# math.atan(x) 返回以弧度为单位的x的反正切值
print(math.atan(1))

2.sin()、cos()、tan()

import math

# math.sin(x) 返回以弧度为单位的x的正弦值
print(math.sin(math.pi / 2))
# math.cos(x) 返回以弧度为单位的x的余弦值
print(math.cos(math.pi))
# math.tan(x) 返回以弧度为单位的x的正切值
print(math.tan(math.pi / 4))

输出:

1.0
-1.0
0.9999999999999999

常量

import math

# math.pi 常数3.141592……
# math.e  常数2.718283……
# math.tau常数6.283185等于2pi
# math.inf浮点数无穷大
# math.nan浮点非数字
print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)
print(math.nan)

输出:

3.141592653589793
2.718281828459045
6.283185307179586
inf
nan

猜你喜欢

转载自blog.csdn.net/qq_45985728/article/details/123924422