summaryrefslogtreecommitdiff
path: root/845/CH2/EX2.1/Ex2_1.sce
diff options
context:
space:
mode:
authorpriyanka2015-06-24 15:03:17 +0530
committerpriyanka2015-06-24 15:03:17 +0530
commitb1f5c3f8d6671b4331cef1dcebdf63b7a43a3a2b (patch)
treeab291cffc65280e58ac82470ba63fbcca7805165 /845/CH2/EX2.1/Ex2_1.sce
downloadScilab-TBC-Uploads-b1f5c3f8d6671b4331cef1dcebdf63b7a43a3a2b.tar.gz
Scilab-TBC-Uploads-b1f5c3f8d6671b4331cef1dcebdf63b7a43a3a2b.tar.bz2
Scilab-TBC-Uploads-b1f5c3f8d6671b4331cef1dcebdf63b7a43a3a2b.zip
initial commit / add all books
Diffstat (limited to '845/CH2/EX2.1/Ex2_1.sce')
-rwxr-xr-x845/CH2/EX2.1/Ex2_1.sce56
1 files changed, 56 insertions, 0 deletions
diff --git a/845/CH2/EX2.1/Ex2_1.sce b/845/CH2/EX2.1/Ex2_1.sce
new file mode 100755
index 000000000..500b7c858
--- /dev/null
+++ b/845/CH2/EX2.1/Ex2_1.sce
@@ -0,0 +1,56 @@
+//Example 2.1
+clc
+clear
+
+function [root] = Bisection(fun,x,tol,maxit)
+// Bisection: Computes roots of the function in the given range using Bisection Method
+//// Input: Bisection(fun,x,tol,maxit)
+// fun = function handle
+// x = range in between sign change is evident
+// tol = Maximum error between iterations that can be tolerated
+// maxit = Maximum number of iterations
+//// Output: [root]
+// Root: Root of the given function in defined range
+
+if fun(x(1)) > 0 then
+ xu = x(1); xl = x(2);
+else
+ xu = x(2); xl = x(1);
+end
+
+Ea = 1;
+iter = 1;
+
+while(1)
+ xr(iter) = (xl(iter) + xu(iter)) / 2;
+ if fun(xr(iter)) > 0 then
+ xu(iter+1) = xr(iter);
+ xl(iter+1) = xl(iter);
+ elseif fun(xr(iter)) < 0 then
+ xl(iter+1) = xr(iter);
+ xu(iter+1) = xu(iter);
+ else
+ break
+ end
+
+ if iter>1 then
+ Ea(iter) = 100 * abs((xr(iter) - xr(iter-1)) / xr(iter));
+ end
+
+ if Ea(iter) < tol | iter == maxit then
+ break
+ end
+ iter = iter + 1;
+end
+root = xr(iter);
+endfunction
+
+function f = fun1(x)
+ f = x.^3 -9*x + 1;
+endfunction
+
+x = [2 4];
+tol = 1e-4;
+maxit = 5;
+root = Bisection(fun1,x,tol,maxit);
+disp(root,"root = ")