Skip to content

Instantly share code, notes, and snippets.

@pureexe
Created December 26, 2017 05:23
Show Gist options
  • Select an option

  • Save pureexe/21c4a9f56a4dbb1846cc32dc4f6275be to your computer and use it in GitHub Desktop.

Select an option

Save pureexe/21c4a9f56a4dbb1846cc32dc4f6275be to your computer and use it in GitHub Desktop.
#include<stdio.h>
double func(double x){
return x*x;
}
double trapzoid(double (*f)(double),double a,int n,double b){
int k;
double sum_odd = 0, sum_even = 0,h;
n = n * 2; //simpson จะแบ่งช่วงย่อยเป็นช่วงคู่และช่วงคี่
h = (b-a)/n;
for(k = 0;k<n - k;k++){
sum_odd+= f(a+h+2*k*h);
}
for(k = 1;k<n - k;k++){
sum_even+= f(a+2*k*h);
}
return (h/3)*(f(a)+4*sum_odd+2*sum_even+f(b));
}
int main(){
double result = trapzoid(func,0.5,100,1);
double exact = (1.0/3) - (0.125/3);
printf("Integrate x^2 from 0.5 to 1\nSimpson = %.6f\nExact = %.6f",result,exact);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment