数学运算难不倒你:Python中常用的数学库函数
发布时间:2023-06-16 16:37:30
Python作为一门高级编程语言,拥有丰富的数学库函数,让数学运算变得十分容易。这篇文章将会简单介绍一些常用的数学库函数。
1. math库
Python的math库提供了许多常用的数学函数,比如sin、cos、tan、log等等。以下是一些常用的函数:
import math # 取整函数 print(math.ceil(2.4)) # 输出 3 print(math.ceil(2.0)) # 输出 2 print(math.ceil(-2.4)) # 输出 -2 print(math.ceil(-2.0)) # 输出 -2 print(math.floor(2.4)) # 输出 2 print(math.floor(2.0)) # 输出 2 print(math.floor(-2.4)) # 输出 -3 print(math.floor(-2.0)) # 输出 -2 # 幂和平方根函数 print(math.pow(2, 3)) # 输出 8.0 print(math.sqrt(4)) # 输出 2.0 # 三角函数 print(math.sin(math.pi / 2)) # 输出 1.0 print(math.cos(math.pi / 2)) # 输出 6.123233995736766e-17 print(math.tan(math.pi / 2)) # 输出 1.633123935319537e+16 # 对数函数 print(math.log(100, 10)) # 输出 2.0 print(math.log(100)) # 输出 4.605170185988092
2. random库
Python的random库提供了随机数生成器。以下是一些常用的函数:
import random # 随机数生成函数 print(random.random()) # 输出 0.6566018588857784 print(random.randint(1, 10)) # 输出 7 print(random.choice(['apple', 'banana', 'orange'])) # 随机输出 'banana' # 打乱列表顺序 my_list = ['apple', 'banana', 'orange'] random.shuffle(my_list) print(my_list) # 随机输出 ['orange', 'apple', 'banana']
3. numpy库
Python的numpy库是一款科学计算的常用库。以下是一些常用的函数:
import numpy as np # 数组生成函数 a = np.array([1, 2, 3]) print(a) # 输出 [1 2 3] b = np.zeros(3) print(b) # 输出 [0. 0. 0.] c = np.ones(3) print(c) # 输出 [1. 1. 1.] d = np.linspace(0, 1, 5) print(d) # 输出 [0. 0.25 0.5 0.75 1.] # 数组加减乘除函数 a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(a + b) # 输出 [5 7 9] print(a - b) # 输出 [-3 -3 -3] print(a * b) # 输出 [4 10 18] print(a / b) # 输出 [0.25 0.4 0.5 ]
4. scipy库
Python的scipy库是一个高级的科学计算库,提供了像优化、解释器等高级功能。下面是一些常用的函数:
import scipy as sp
# 矩阵求逆函数
a = sp.array([[1, 2], [3, 4]])
b = sp.linalg.inv(a)
print(b) # 输出 [[-2. 1.]
# [ 1.5 -0.5]]
# 最小二乘拟合函数
x = sp.array([0, 1, 2, 3, 4])
y = sp.array([1, 3, 7, 13, 21])
sp.polyfit(x, y, 1)
print ((2.20151515, 1.04242424)) # 输出 (2.20151515, 1.04242424)
以上是一些常用的数学库函数。当然,Python的数学库不只这些,根据不同的场景和需求,我们可以选择更加适合的数学库函数。
