解方程组
程序员文章站
2022-03-05 20:26:19
...
通过使用scipy.optimize中的fsolve函数或broyden1函数,解三元方程组的解,并将解代入原方程验证(f1,f2,f3均接近于0),程序代码:
import scipy.optimize as opt
from numpy import exp
import timeit
st1 = timeit.default_timer()
def f(variables):
(x, y,z) = variables
first_eq = x + y**2 +2*z- 4
second_eq = exp(x) + x*y-z**2 - 3
third_eq=x**2-y*z+z**2-2
return [first_eq, second_eq,third_eq]
solution = opt.fsolve(f, (0.1,0.5,1)) # solution = opt.broyden1(f,(0.1,0.5,1))
print(solution)
st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))
x, y, z = solution[0],solution[1],solution[2]
print(f'f1={f((x,y,z))[0]}')
print(f'f2={f((x, y, z))[1]}')
print(f'f3={f((x, y, z))[2]}')
运行结果:
[1.2298751 0.70637 1.13558316]
RUN TIME : 0.0009333000000000258
f1=-2.9887203822909214e-13
f2=-3.907985046680551e-14
f3=2.05613304160579e-13