Created
December 26, 2017 05:23
-
-
Save pureexe/21c4a9f56a4dbb1846cc32dc4f6275be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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