C++ | Using Simpsons Rule to Numerically integrate an equation !

So here is the code and the explanation below :

#include <iostream>
#include <cmath>
using namespace std;

main(){
    int a,b,n;
    cout << "Enter upper limit, b:"; cin >> b;
    cout << "Enter lower limit, a:"; cin >> a;
    cout << "\nEnter number of Simpson's interval, n (even number only):"; cin >> n;
    long double dx, t=0;
    dx = (long double)(b-a)/n;
    long double fx[n+1];
    for(int i=0;i<=n;i++){
        if (i == 0){
            t = a;
        }
        else if (i == n){
            t = b;
        }
        else{
            t = a+(i*dx);
        }
        //cout << "t = " << t << endl; // im just curious to know
        fx[i] = (1.36*pow(10,-10))*t*t*t*t - (1.23*pow(10,-7))*t*t*t + (4.12*pow(10,-6))*t*t + (3.95*pow(10,-4))*t - (8.58*pow(10,-2));
        //fx[i] = (double)1 / (t + 1 );
        //cout << "fx[" << i << "] = " << fx[i] << endl; // im just curious to know
    }
    long double sum = 0, area = 0;
    for (int i=0;i<=n;i++){
            if (i == 0 || i == n){
                sum = sum + fx[i];
            }
            else if( i%2 == 0){
                sum = sum + 2*fx[i];
            }
            else {
                sum = sum + 4*fx[i];
            }
    }
    area = (dx/3)*sum;
    cout << "sum = " << sum << endl;
    cout << "dx = " << dx << endl;
    cout << "\nThe Area is = " << area << endl;
    return 0;
}


This program will find the integral of this equation using Simpson's rule:

y = (1.36x10^-10)t^4 - (1.23x10^-7)t^3 + (4.12x10^-6)t^2 + (3.95x10^-4)t 
      - (8.58x10^-2)
I write in primitive programming instead of using OOP. But of course you can convert it into OOP instead. And of course you can change the equation with your own.

The program accept the upper limit and lower limit and then accept the interval for the simpson's rule. It will then calculate delta x. Next it will enter a loop which will calculate the simpson's rule. You can google for more info on how to use simpson's rule or to verify the answer from this program. As usual, you can modify or alter this code freely and I does not responsible for any misuse, accident, misunderstanding or anything you do while using this code.

*Note that: Interval for simpson's rule must always in even number !

Don't forget to say thanks and leave your question or suggestion down below !

(* I used Code::Blocks the open source cross-platform IDE on windows 7)

So here is the sample output:


Popular posts from this blog

Extra : Play DOTA 2 Offline The Simplified Way

Create a Custom Blogger Header Part 2

Tips Tingkatkan Kelajuan Blog