# 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
```
xn
∫ f(x) dx = (h/2) [Sum of extreme ordinates + 2(Sum of intermediate ordinates)]
x0

```
to implement scilab program for trapezoidal rule. The program below is successfully executed on Scilab 6.0.2.

## 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.

Now define the function in the console and invoke (call) it with appropriate arguments. Example output is shown below.

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.