Skip to content

Instantly share code, notes, and snippets.

@lefty313
Created May 23, 2011 13:24
Show Gist options
  • Save lefty313/986688 to your computer and use it in GitHub Desktop.
Save lefty313/986688 to your computer and use it in GitHub Desktop.
trapezoidal integration
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
/*
Wedlug wolfram alfa pole zaznaczone przez ta calke od 2 do 4 wynosi w przyblizeniu = 65.8758
http://www.wolframalpha.com/input/?i=integral+x^2+%2B+e^x+from+2+to+4
Aby uzyskac taki wynik w moim algorytmie nalezy ustawic dokladnosc calkowania na 350
Funkcja dla ktorej obliczamy calke
*/
float integral_function(float x) {
return pow(x,2) + pow(M_E,x);
}
int main(){
float begin, end, dx, integral;
int i, n;
// Wczytanie danych
printf("Poczatek przedzialu calkowania\n");
scanf("%f", &begin);
printf("Koniec przedzialu calkowania\n");
scanf("%f", &end);
printf("Dokladnosc calkowania\n");
scanf("%d", &n);
// Wysokosc jednego trapezu
dx = (end - begin) / n;
// Poczatkowa wartosc calki
integral = 0;
// Petla sumujaca kolejne pola trapezow. W kazdej iteracji jest sumowane pole kolejnego trpezu zaczynajac od "begin"
for (i=1; i<n; i++) {
integral += integral_function(begin + i * dx);
}
integral = (integral + (integral_function(begin) + integral_function(end)) / 2) * dx;
printf("Wartosc calki w przyblizeniu wynosi %f\n", integral);
getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment