Simpson’s 1/3rd Rule Integration SCILAB CODE(Program/Macro)

The following is the code for evaluating a definite integral of a given function by a Numerical Method called Simpson’s 1/3rd Rule.

DOWNLOAD:simpson

funcprot(0);
function ans=simpson(a,b,n,g)
    h=(b-a)/n;
    sum=0;
    for i=1:n-1
        x=a+i*h;
        if modulo(i,2)==0
            sum=sum+2*g(x);
        else 
            sum=sum+4*g(x);
        end 
    end
    ans=(h/3)*(g(a)+g(b)+sum);
endfunction


You can either copy the code above and save it as a .sci file or download the file simpson . Once you run the code, the function ‘simpson(a,b,n,f)’ can be called by other programs or even in the console.

Function syntax:

simpson(a,b,n,f)

where,

a=initial limit(real no.)
b=final limit(real no.)
n=no. of sub-intervals(the higher the value of ‘n’ the better is the result.
NOTE: n should be an even no.

Example:
The following code snippet evaluates the integral of x^4 from 0 to 2.

deff('a=f(x)','a=x^4');
integral=simpson(0,2,30,f);

Here is a comparison of the result with the inbuilt function ‘intg’.

Capture

[wpedon id="7041" align="center"]

3 thoughts on “Simpson’s 1/3rd Rule Integration SCILAB CODE(Program/Macro)

  1. Hi! I’m having trouble with this code, when I run it with an “x” amount of sub-intervals it returns a correct number, but when I run it with a lower numer of sub-intervals it returns an even closer number to the exact result.
    Did you find this error too? How did you solve it?
    Thanks

  2. A follow-up to my previous comment:

    I have the exact result of an integral, when I run the code that you submitted with 2 sub-intervals, the number of error I get is 7*10^-5. But when I run it with 10 sub-intervals, the number of error I get is 3*10^-4.

    So, the lower the number of sub-intervals, the better is the result.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.