python迭代法求解非线性方程_荐【数学知识】非线性方程求解的二分法以及牛顿迭代法...
【數(shù)學(xué)知識(shí)】非線性方程求解的二分法以及牛頓迭代法
本博客不談及理論推導(dǎo),只提供代碼實(shí)現(xiàn),關(guān)于理論推導(dǎo),大家可以查看其它博客文章。
導(dǎo)入包
import sys
import math
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
二分法
class ConditionError(Exception):
def __init__(self,ErrorInfo):
super().__init__(self)
self.errormsg = ErrorInfo
def __str__(self):
return self.errormsg
def BisectionMethod(f,a,b,err=1e-5,max_iter=100):
'''A root-finding method:Bisection method.
Args
----------
f: callable function
The nonlinear function to be solved.
a,b: float
The initial interval, which satisfies the condition:a
err: float
Tollerence of the result.
max_iter: int
Maximun iterations.
Outs
----------
x0: float
The root between interval [a,b].
tol: float
Tollerence of the result.
iters:
Number of iterations when the method stopped.
'''
if a>b:
raise ConditionError('Wrong interval setup,it must be: a
if (f(a)>0 and f(b)>0) or (f(a)<0 and f(b)<0):
print("Can't find the root of function as the condition is insurficient!")
n = 1
while n
c = (a+b)/2
print("n={},c={}".format(n,f(c)))
if f(c)==0 or (b-a)/2
x0=c
break
n += 1
if f(a)*f(c)>0:
a = c
else:
b = c
print("求解結(jié)果:n={},tol={},x0={}".format(n,abs(f(x0)),x0))
tol, iters = abs(f(x0)), n
return x0,tol,iters
問題1
求解方程
(x+5)(x?1)(x?3)=0(x+5)(x-1)(x-3)=0(x+5)(x?1)(x?3)=0
求解步驟:
1、畫圖確定根的大致位置,選擇根的初始區(qū)間[a,b]
2、使用二分法函數(shù)BisectionMethod進(jìn)行求解
def f(x):
'''Nonlinear function to be solved
$f(x)=(x+5)(x-1)(x-3)$
'''
return (x+5)*(x-1)*(x-3)
x = np.linspace(-6, 6, num = 1000)
y = f(x)
plt.plot(x,y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none') # 將右邊 上邊的兩條邊顏色設(shè)置為空 其實(shí)就相當(dāng)于抹掉這兩條邊
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') # 指定下邊的邊作為x軸 指定左邊的邊為y軸
ax.spines['bottom'].set_position(('data', 0)) #指定data設(shè)置的bottom(也就是指定的x軸)綁定到y(tǒng)軸的0這個(gè)點(diǎn)上
ax.spines['left'].set_position(('data', 0))
BisectionMethod(f,-7,4,err=1e-5)
n=1,c=39.375
n=2,c=28.546875
n=3,c=-35.712890625
n=4,c=2.945556640625
n=5,c=-14.629669189453125
n=6,c=-5.418788909912109
n=7,c=-1.1327033042907715
n=8,c=0.9321668744087219
n=9,c=-0.09380341321229935
n=10,c=0.4207942122593522
n=11,c=0.16389898478519171
n=12,c=0.03514874020766001
n=13,c=-0.029302090633791522
n=14,c=0.002929635346163195
n=15,c=-0.01318464989051904
n=16,c=-0.005127112848040127
n=17,c=-0.0010986401466772655
n=18,c=0.000915522250586609
n=19,c=-9.155278530671024e-05
n=20,c=0.0004119862733211405
n=21,c=0.00016021712917794583
求解結(jié)果:n=21,tol=0.00016021712917794583,x0=-4.999996662139893
(-4.999996662139893, 0.00016021712917794583, 21)
BisectionMethod(f,0,2,err=1e-5)
n=1,c=-0.0
求解結(jié)果:n=1,tol=0.0,x0=1.0
(1.0, 0.0, 1)
BisectionMethod(f,2,4,err=1e-5)
n=1,c=0.0
求解結(jié)果:n=1,tol=0.0,x0=3.0
(3.0, 0.0, 1)
編程作業(yè)
使用二分法求解以下方程的根:
x2?ex=0x^2-e^x=0x2?ex=0
# 請(qǐng)?jiān)诖藚^(qū)域書寫求解代碼
牛頓迭代法
使用到包sympy
sympy教程:https://geek-docs.com/python/python-tutorial/python-sympy.html
SymPy 是用于符號(hào)數(shù)學(xué)的 Python 庫。 它旨在成為功能齊全的計(jì)算機(jī)代數(shù)系統(tǒng)。 SymPy 包括從基本符號(hào)算術(shù)到微積分,代數(shù),離散數(shù)學(xué)和量子物理學(xué)的功能。 它可以在 LaTeX 中顯示結(jié)果。
SymPy 是使用pip install sympy命令安裝的。
t = np.linspace(-5,5,100)
y = t*np.exp(t)-100
plt.plot(t,y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none') # 將右邊 上邊的兩條邊顏色設(shè)置為空 其實(shí)就相當(dāng)于抹掉這兩條邊
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') # 指定下邊的邊作為x軸 指定左邊的邊為y軸
ax.spines['bottom'].set_position(('data', 0)) #指定data設(shè)置的bottom(也就是指定的x軸)綁定到y(tǒng)軸的0這個(gè)點(diǎn)上
ax.spines['left'].set_position(('data', 0))
def NewtonMethod(f,x0,err=1e-5,max_iter=1000):
'''A root-finding method:Newton method.
Args
----------
f: callable function
The nonlinear function to be solved.
x0: float
The initial x0
err: float
Tollerence of the result.
max_iter: int
Maximun iterations.
Outs
----------
result: float
The root between interval.
'''
x=sp.symbols("x")
f=sp.integrate(f, x) # 先求不定積分
f=sp.diff(f) # 再求導(dǎo)
if sp.diff(f).subs(x,x0)==0:
return x0
n=1
x_new=x0
while n<=max_iter:
x_new=x0-f.subs(x,x0)/sp.diff(f).subs(x,x0)
#x_new=float(x_new)
if math.fabs(x_new-x0)
return float(x_new)
x0=x_new
n+=1
print("無法在設(shè)定的循環(huán)步數(shù)內(nèi)獲得指定精度的近似解")
return float(x_new)
x=sp.symbols("x") # 定義符號(hào)
f=x*sp.exp(x)-100 # 需要注意,各種初等函數(shù)符號(hào),例如exp,cos,sin等,均需要使用sympy指定的符號(hào)構(gòu)建
x0 = 3
xr = NewtonMethod(f,x0,err=1e-3,max_iter=1000)
print("求根結(jié)果:", float(xr))
求根結(jié)果: 3.385630140831713
編程作業(yè)
使用牛頓迭代法求解以下方程的根:
x3?ex=0x^3-e^x=0x3?ex=0
# 請(qǐng)?jiān)诖藚^(qū)域書寫求解代碼
【作者簡介】陳藝榮,男,目前在華南理工大學(xué)電子與信息學(xué)院廣東省人體數(shù)據(jù)科學(xué)工程技術(shù)研究中心攻讀博士,擔(dān)任IEEE Access、IEEE Photonics Journal的審稿人。兩次獲得美國大學(xué)生數(shù)學(xué)建模競賽(MCM)一等獎(jiǎng),獲得2017年全國大學(xué)生數(shù)學(xué)建模競賽(廣東賽區(qū))一等獎(jiǎng)、2018年廣東省大學(xué)生電子設(shè)計(jì)競賽一等獎(jiǎng)等科技競賽獎(jiǎng)項(xiàng),主持一項(xiàng)2017-2019年國家級(jí)大學(xué)生創(chuàng)新訓(xùn)練項(xiàng)目獲得優(yōu)秀結(jié)題,參與兩項(xiàng)廣東大學(xué)生科技創(chuàng)新培育專項(xiàng)資金、一項(xiàng)2018-2019年國家級(jí)大學(xué)生創(chuàng)新訓(xùn)練項(xiàng)目獲得良好結(jié)題,發(fā)表SCI論文4篇,授權(quán)實(shí)用新型專利8項(xiàng),受理發(fā)明專利13項(xiàng)。
我的主頁
我的Github
我的CSDN博客
我的Linkedin
原文鏈接:https://blog.csdn.net/m0_37201243/article/details/105953253
總結(jié)
以上是生活随笔為你收集整理的python迭代法求解非线性方程_荐【数学知识】非线性方程求解的二分法以及牛顿迭代法...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: python两个数相加时_两数相加 le
 - 下一篇: python获取控制台输出_Python