numpy矩阵运算:
import numpy as np
A = np.array([1, 2, 3])
T = np.transpose(A) # 矩阵转置
print(A.dot(T)) # 矩阵乘法
B = np.array([[1, 2, 3], [2, 2, 1], [3, 4, 3]])
print(np.linalg.inv(B)) # 矩阵求逆
sympy求导数:
import numpy as np
from sympy import *
x = symbols("x")
e = np.e
f = log(1 + e ** x) / (1 + e ** (-x))
# 一阶导数
f1 = diff(f, x, 1)
# 二阶导数
f2 = diff(f, x, 2)
# 三阶导数
f3 = diff(f, x, 3)
print(f1, f2, f3, sep='\n')
sympy求偏导数:
from sympy import *
x1, x2 = symbols("x1, x2")
f = (x1 - 1) ** 2 + 100 * (x2 - x1 ** 2) ** 2
fx1 = diff(f, x1) # 偏导数
fx2 = diff(f, x2)
print(diff(fx1, x1)) # 二阶偏导数
print(diff(fx1, x2))
print(diff(fx2, x1))
print(diff(fx2, x2))
sympy求不定积分:
from sympy import *
x = symbols("x")
f = log(x)
str = integrate(f, x) # 不定积分
print(str)
scipy求定积分:
from scipy import integrate
import numpy as np
def f(x, y):
return 6 - x - y
# 二重积分,参数为先x的下限和上限,后y的下限和上限,err为误差
ans, err = integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 4 - x)
print(ans / 24)
# 一重积分
ans, err = integrate.quad(lambda x: x ** 2 - 12 * x + 32, 0, 2)
print(ans / 48)
def w(x):
return 1 / np.sqrt(abs(x))
# w函数在x=0处存在断点 用quad()函数中的points可跳过求解
ans, err = integrate.quad(w, -1, 1, points=[0])
print(ans)