Wednesday, May 1, 2013

Integrasi Numerik

Pada kesempatan kali ini saya ingin berbagi ilmu tentang kompeetensi numerik. Disini saya ingin berbagai cara menyelesaikan suatu kasus menggunakan metode integrasi numerik dengan menggunakan program c++. Berikut source codenya:

#include <stdio.h>
#include <math.h>
#include <conio.h>

float jumlah_atas(float, float, float);
float jumlah_bawah(float, float, float);
float trapezoida(float, float, float);

float f(float);

int main(){
     float batas_atas;
     float batas_bawah;
     int jumlah_h = 20;

     printf("Masukkan batas atas : ");
     scanf("%f", &batas_atas);
     printf("Masukkan batas bawah : ");
     scanf("%f", &batas_bawah);
     printf("Masukkan jumlah h : ");
     scanf("%d", &jumlah_h);

     printf("Jumlah atas  : %20.18f \n",
     jumlah_atas(batas_bawah, batas_atas, jumlah_h));
     printf("Jumlah bawah : %20.18f \n",
     jumlah_bawah(batas_bawah, batas_atas, jumlah_h));
     printf("Rata-rata    : %20.18f \n\n",
     (jumlah_atas(batas_bawah, batas_atas, jumlah_h) + jumlah_bawah(batas_bawah, batas_atas, jumlah_h)) /2);
     printf("Jumlah trapezoida  : %20.18f \n", trapezoida(batas_bawah, batas_atas, jumlah_h));
}

/*definisi fungsi yang akan dicari nilainya*/
float f(float x){
     return exp(x)*sin(x);
}

/* mencari nilai luas dengan metode jumlah atas */
float jumlah_atas(float bwh, float ats, float jlh){
     float i, luas = 0;
     float node1, node2;
     float y_node1, y_node2, y;
     float lebar_segmen = (ats - bwh) / jlh;
     for(i = bwh; i < ats; i += lebar_segmen){
           node1 = i;
           node2 = i + lebar_segmen;
     y_node1 = f(node1);
     y_node2 = f(node2);
     if(y_node1 < y_node2)
           y = y_node1;
     else
           y = y_node2;

     luas += lebar_segmen * y;
     }
     return luas;
}

/* mencari nilai luas dengan metode jumlah bawah */
float jumlah_bawah(float bwh, float ats, float jlh){
     float i, luas = 0;
     float node1, node2;
     float y_node1, y_node2, y;
     float lebar_segmen = (ats - bwh) / jlh;
     for(i = bwh; i < ats; i += lebar_segmen){
           node1 = i;
           node2 = i + lebar_segmen;
           y_node1 = f(node1);
           y_node2 = f(node2);
           if(y_node1 > y_node2)
                y = y_node1;
           else
                y = y_node2;

           luas += lebar_segmen * y;
     }
     return luas;
}

/* mencari nilai luas dengan metode trapezoidal */
float trapezoida(float bwh, float ats, float jlh){
     int i;
     float luas = 0;
     float lebar_segmen = (ats - bwh) / jlh;
     float node, y;

     luas = 0.5 * lebar_segmen * (f(ats) + f(bwh));
     for(i = 1; i < jlh; i++){
           node = bwh + i * lebar_segmen;
           y = f(node);
           luas += lebar_segmen * y;
     }
     return luas;
   getch();
}

 Dan hasil dari script tersebut adalah:

Sekian ilmu yang dapat saya bagi. Semoga bermanfaat, terima kasih.

0 comments:

Post a Comment