使用scipy库的root和fsolve函数求解方程

求解非线性方程

使用scipy库的 root, fsolve 函数求解非线性方程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from scipy.optimize import fsolve
from scipy.optimize import root


def func(x):
return x ** 4 - x - 5


x_root = root(func, 1.0)
x_fsolve = fsolve(func, 1.0)
print(x_root.x)
print(x_fsolve)

# [1.60300708]
# [1.60300708]

求解传热方程(热辐射+热传导)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from scipy.optimize import fsolve


# 热流密度q, w/m2
# 方程为 q = k1 * (t0 ** 4 - t1 ** 4) + k2 * (t0 - t1)
def solver(q, t0):
def func(t1):
eps1, eps2 = 0.1, 0.8 # 表面发射率 epsilon
lam = 0.04 # 热导率 lamda, w/(m.k)
dx = 0.005 # 材料的厚度, m
k1 = 5.67e-8 / (1 / eps1 + 1 / eps2 - 1)
k2 = 0.016 * lam / dx
return k1 * (t0 ** 4 - t1 ** 4) + k2 * (t0 - t1) - q

x = fsolve(func, t0 - 0.01)
return x[0]


t = solver(q=1.0, t0=300.)
print(t)

# 298.6136062486314

ref: