Scilab Program for Trapezoidal Rule Integration
Problem:
Write a scilab program for trapezoidal rule. Write a program for solving a definite integral using trapezoidal rule in scilab.Solution:
Illustration of "chained trapezoidal rule" used on an irregularly-spaced partition of [a,b]. Author: Cdang
In numerical analysis, the trapezoidal rule integration is used to evaluate a definite integral using a numerical method called as trapezoidal rule. The trapezoidal rule formula is
to implement scilab program for trapezoidal rule. The program below is successfully executed on Scilab 6.0.2.xn∫ f(x) dx = (h/2) [Sum of extreme ordinates + 2(Sum of intermediate ordinates)] x0
Scilab Program / Source Code:
Here is the scilab code/program for evaluating definite integral using trapezoidal rule// Aim: Write a scilab program for trapezoidal rule formula
deff('y=f(x)','y=1/(1+x^2)'); // define the function
x=0:0.2:1; // divide the range into subintervals, here interval length is 0.2
n=length(x); // store total number of elements in range
h=x(2)-x(1); // store subinterval length
sum=0; // initialize a variable to store final value
// loop to evaluate final value
for i=1:n
if i==1 | i==n then // sum up first and last value
sum=sum+f(x(i));
else
sum=sum+2*f(x(i)); // multiply and then sum up for intermediate values
end
end
sum=sum*(h/2); // multiply result by h/2
disp(sum); // display the result
Scilab code for trapezoidal rule using function
function final_ans=trapezoidal_rule(lower_limit,upper_limit,n,f)
h=(lower_limit+upper_limit)/n;
sum=0;
for i=1:n-1
arg=lower_limit+i*h;
sum=sum+2*f(arg);
end
final_ans=(h/2)*(f(lower_limit)+f(upper_limit)+sum);
disp(final_ans)
endfunction
Open sci-notes, paste and save the function as .sci file. Click on execute as shown in the image below.
![How to execute scilab function for trapezoidal rule How to execute scilab function for trapezoidal rule](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNlrAQ_JIFAdeZQ0Z70YbZr7xbLbW6cUDWlKCkRPYij2gnJbo7HSOnE3FKYxZn4i2VAujVw43I4weXjFgZgsrhKBjPfk8jwAR1yt4ocEsweSAfF8tDbURLRot7eYqd0pFRq4EfnvFAGcYT/s1600/how_to_scilab_code_for_trapezoidal_rule.png)
Now define the function in the console and invoke (call) it with appropriate arguments. Example output is shown below.
![Output of scilab program for trapezoidal rule Output of scilab program for trapezoidal rule](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdHKN59Wu8Q4L9lBB32Bj8HP9eckno0bLub1XPjyWHydCRhoq6rM6WnR_wnupEc6pmKWod-eWQcZi135DhA4wE2OA4ltcMmaABd6zugvgO77I8xXhUl_0Q6rCG1SgD9-9AyT8nh2oPPW2Q/s1600/output_of_scilab_program_for_trapezoidal_rule.png)
Trapezoidal rule is efficient if we want smaller errors for same number of intervals. But In general if you want the most efficient method of evaluating a definite integral function, it is simpsons rule.