本文总结了一些简单的Python数学操作,如均值、方差、标准差,函数方程,求导等
# 数据集
# 1, 2, 3, 4, 5
import numpy as np
arr = [1, 2, 3, 4, 5]
# 均值
arr_mean = np.mean(arr)
print("arr均值=%f" % arr_mean)
# 方差
arr_var = np.var(arr)
print("arr方差=%f" % arr_var)
# 标准差
arr_std = np.std(arr)
print("arr标准差=%f" % arr_std)
输出
arr均值=3.000000
arr方差=2.000000
arr标准差=1.414214
# 题目
# 2x-8=0
from sympy import *
x= symbols('x')
print(solve(2 * x - 8,x))
输出
[4]
# 题目
# 3x−y=3
# 3x+y=9
from sympy import *
x, y = symbols('x,y')
print(solve([3 * x - y - 3, 3 * x + y - 9], [x, y]))
输出
{x: 2, y: 3}
# 题目
# x²+2x+1=0
from sympy import *
x = symbols('x')
print(solve(x ** 2 + 2 * x + 1, x))
输出
[-1]
# 题目:
# x₁+3x₂+4x₃=8
# 2x₁+x₂+6x₃=12
# 2x₁+3x₂+4x₃=3
import numpy as np
import scipy as sp
import scipy.linalg
a = np.array([[1, 2, 2], [3, 1, 6], [4, 5, 4]])
b = np.array([8, 12, 3])
print(sp.linalg.solve(a, b))
输出:
[-7.7 2.4 5.45]
# 题目
# 5x₁+3=0
# 4x₃²-2sin(x₁x₂)=0
# x₁x₂-1.5=0
from math import sin, cos
from scipy import optimize
def f(x):
x1, x2, x3 = x.tolist()
return [5 * x1 + 3, 4 * x3 * x3 - 2 * sin(x1 * x2), x1 * x2 - 1.5]
# f 计算方程组的误差,[1,1,1]是未知数的初始值
result = optimize.fsolve(f, [1, 1, 1])
print(result) # x1,x2,x3的值
print(f(result)) # 方程组的误差
输出
[-0.6 -2.5 -0.70622057]
[0.0, -9.126033262418787e-14, 5.329070518200751e-15]
# 题目
# 已知f(x) = x**2
# 求f'(x)
# 求f'(1)
x = Symbol('x')
y = x ** 2
dx = diff(y, x)
print("y =", dx)
u = lambdify(x, dx)
print(u(1))
输出
y = 2*x
2
# 题目
# 已知f(x)=2x**2+3x
# 求f'(x)
# 求f'(1)
def f(x):
return 2 * x ** 2 + 3 * x ** 2
print(derivative(f, 1))
输出
10.0