python scipy求解非线性方程的方法(fsolve/root)
Python  /  管理员 发布于 7年前   163
使用scipy.optimize模块的root和fsolve函数进行数值求解线性及非线性方程,下面直接贴上代码,代码很简单
from scipy.integrate import odeintimport numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import root,fsolve#plt.rc('text', usetex=True) #使用latex## 使用scipy.optimize模块的root和fsolve函数进行数值求解方程## 1、求解f(x)=2*sin(x)-x+1rangex1 = np.linspace(-2,8)rangey1_1,rangey1_2 = 2*np.sin(rangex1),rangex1-1plt.figure(1)plt.plot(rangex1,rangey1_1,'r',rangex1,rangey1_2,'b--')plt.title('$2sin(x)$ and $x-1$')def f1(x): return np.sin(x)*2-x+1sol1_root = root(f1,[2])sol1_fsolve = fsolve(f1,[2])plt.scatter(sol1_fsolve,2*np.sin(sol1_fsolve),linewidths=9)plt.show()## 2、求解线性方程组{3X1+2X2=3;X1-2X2=5}def f2(x): return np.array([3*x[0]+2*x[1]-3,x[0]-2*x[1]-5])sol2_root = root(f2,[0,0])sol2_fsolve = fsolve(f2,[0,0])print(sol2_fsolve) # [2. -1.5]a = np.array([[3,2],[1,-2]])b = np.array([3,5])x = np.linalg.solve(a,b)print(x) # [2. -1.5]## 3、求解非线性方程组def f3(x): return np.array([2*x[0]**2+3*x[1]-3*x[2]**3-7, x[0]+4*x[1]**2+8*x[2]-10, x[0]-2*x[1]**3-2*x[2]**2+1])sol3_root = root(f3,[0,0,0])sol3_fsolve = fsolve(f3,[0,0,0])print(sol3_fsolve)## 4、非线性方程def f4(x): return np.array(np.sin(2*x-np.pi)*np.exp(-x/5)-np.sin(x))init_guess =np.array([[0],[3],[6],[9]])sol4_root = root(f4,init_guess)sol4_fsolve = fsolve(f4,init_guess)print(sol4_fsolve)t = np.linspace(-2,12,2000)y1 = np.sin(2*t-np.pi)*np.exp(-t/5)y2 = np.sin(t)plt.figure(2)a , = plt.plot(t,y1,label='$sin(2x-\pi)e^{-x/5}$')b , = plt.plot(t,y2,label='$sin(x)$')plt.scatter(sol4_fsolve,np.sin(sol4_fsolve),linewidths=8)plt.title('$sin(2x-\pi)e^{-x/5}$ and $sin(x)$')plt.legend()
以上这篇python scipy求解非线性方程的方法(fsolve/root)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号