python scipy求解非線性方程的方法(fsolve/root)
更新時間:2018年11月12日 14:02:36 作者:落葉_小唱
今天小編就為大家分享一篇python scipy求解非線性方程的方法(fsolve/root),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
使用scipy.optimize模塊的root和fsolve函數(shù)進行數(shù)值求解線性及非線性方程,下面直接貼上代碼,代碼很簡單
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root,fsolve
#plt.rc('text', usetex=True) #使用latex
## 使用scipy.optimize模塊的root和fsolve函數(shù)進行數(shù)值求解方程
## 1、求解f(x)=2*sin(x)-x+1
rangex1 = np.linspace(-2,8)
rangey1_1,rangey1_2 = 2*np.sin(rangex1),rangex1-1
plt.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+1
sol1_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)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決os.path.isdir() 判斷文件夾卻返回false的問題
今天小編就為大家分享一篇解決os.path.isdir() 判斷文件夾卻返回false的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
使用Pandas實現(xiàn)高效讀取篩選csv數(shù)據(jù)
在數(shù)據(jù)分析和數(shù)據(jù)科學(xué)領(lǐng)域中,Pandas?是?Python?中最常用的庫之一,本文將介紹如何使用?Pandas?來讀取和處理?CSV?格式的數(shù)據(jù)文件,希望對大家有所幫助2024-04-04
python庫geopandas讀取寫入空間數(shù)據(jù)及繪圖實例探索
這篇文章主要為大家介紹了python庫geopandas讀取寫入空間數(shù)據(jù)及繪圖實例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪<BR>2024-02-02
Python免費驗證碼識別之ddddocr識別OCR自動庫實現(xiàn)
在Python爬蟲過程中,有些網(wǎng)站需要驗證碼通過后方可進入網(wǎng)頁,目的很簡單,就是區(qū)分是人閱讀訪問還是機器爬蟲,下面這篇文章主要給大家介紹了關(guān)于Python免費驗證碼識別之ddddocr識別OCR自動庫實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2022-02-02
python中的classmethod與staticmethod
這篇文章主要介紹了python中的classmethod與staticmethod,2022-01-01

