用matlab程序写用二分法求方程根

用matlab程序写用二分法求方程根,第1张

二分法在很多地方应该都会见到,这里是通过二分法迭代逼近的方法求出一个方程的根。

function xc = bisection(f,a,b,tol)

% use the bisection method to find the root of the function

% Page 30,computer problem 7(Bisection method)

% input:

% f:the function that transform from the equation

% a,b:the left and right value of the interval which the root is in% tol:the accuracy

% output:

% xc:the solution of the equationif sign(f(a)) * sign(f(b)) >=0

    error('f(a)f(b)<0 not satisfied!')endif nargin < 3

    disp('The function should at least include 3 parameters')endif nargin == 3

    tol = 10^-6endwhile (b-a)/2 > tol

    c = (a + b)/2     

    if f(c) == 0 % when f(c) == 0,c is a root of the function

        break 

    end

    if f(a) * f(c) < 0  

                               % a and c form a new interval

        b = c  else  % c and b form a new interval

        a = c  endendxc = (a+b)/2 % the mid_rang is the root that we find

编程问题,已经给出完整代码,没有相关配图可以配,希望谅解。

参考资料

CSDN.CSDN[引用时间2018-1-9]

matlab源程序如下:

function erfenfa(a,b)%a,b为区间,s=(a+b)/2,while b-a>1e-5  if fun(a)*fun(s)>0。  a=s elseif fun(a)*fun(s)<0

function y=fun(x)

二分法 即一分为二的方法。设[a,b]为R的紧区间, 逐次二分法就是造出如下的区间序列:a0=a,b0=b,且对任一自然数n,[an+1,bn+1]或者等于[an,cn],或者等于[cn,bn],其中cn表示[an,bn]的中点。

一般地,对于函数f(x),如果存在实数c,当x=c时,若f(c)=0,那么把x=c叫做函数f(x)的零点

解方程即要求f(x)的所有零点。

先找到a、b属于区间(x,y),使f(a),f(b)异号,说明在区间(a,b)内一定有零点,然后求f[(a+b)/2],

现在假设f(a)<0,f(b)>0,a<b

如果f[(a+b)/2]=0,该点就是零点,

如果f[(a+b)/2]<0,则在区间((a+b)/2,b)内有零点,(a+b)/2赋给a,从①开始继续使用中点函数值判断。

如果f[(a+b)/2]>0,则在区间(a,(a+b)/2)内有零点,(a+b)/2赋给b,从①开始继续使用中点函数值判断。

通过每次把f(x)的零点所在小区间收缩一半的方法,使区间的两个端点逐步迫近函数的零点,以求得零点的近似值,这种方法叫做二分法。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/10961765.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-12
下一篇 2023-05-12

发表评论

登录后才能评论

评论列表(0条)

保存