Sunday 11 October 2015

Bisection Method Coding in Matlab

clc
close all
clear all
syms x % a variable x has been declared by using syms command.
xl=input('lower value=') % taking  lower value from user.
xu=input('upper value=') % taking upper value from user.
a=input('function=') % input function.
f=inline(a) % inline function for declaring variable.
fxl=subs(f,x,xl) % assigning lower value to fxl by using subs command.
fxu=subs(f,x,xu) % assigning upper value to fxu by using subs command.
if(fxl*fxu>0)
    display('error')
else
    for(i=1:10)       % for loop form 1 to 10
        xr=(xl+xu)/2  % for finding mid point of xl and xu
        fxr=subs(f,x,xr) % assigning lower value to fxl by using subs command.
        if(fxl*fxr<0) % if and else command if fxl*fxu less than 0 then
            xu=xr % putting value of xr to xu.
        else
            xl=xr % putting value of xr tp xr
        end
    end
    root=xr % root showing at 10th iteration.
    xnew(i)=xr
    error=xnew(i)-xnew(i-1)
end
   
lower value=1
xl =  1
upper value=2
xu = 2
function=x^6-x-1
a =x^6 - x - 1
f =Inline function:
     f(x) = -x+x.^6-1.0
fxl =-1
fxu =   61
xr =1.5000
fxr =8.8906
xu =  1.500
xr = 1.250
fxr =1.5647
Xu=1.2500
xr =1.1250
fxr = -0.0977
xl = 1.1250
xr = 1.1875
fxr =0.6167
xu = 1.1875
xul= 1.1563
fxr =0.2333
xu =1.1563
xr =1.1406
fxr =0.0616
xu =  1.1406
xr =1.1328
fxr =-0.0196
xl = 1.1328
xr =1.1367
fxr = 0.0206
xu =1.1367
xr =1.1348
fxr = 4.2684e-004
xu =1.1348
xr =  1.1338
fxr = -0.0096
xl = 1.1338
root = 1.1338
xnew = 0         0         0         0         0         0         0         0         0    1.1338

error =1.1338

No comments:

Post a Comment