|
|
/* Rectangular rule */ #include <stdio.h> double f(double x) {return 4.0/(1.0+x*x) ; } int main() { int i, n; double a=0.0, b=1.0, h, s=0.0 , x ; /* printf("Number of partitions = "); scanf("%d", &n) ; */ n=10; h = (b-a)/n ; for (i= 0;i<n;i++) s = s + f(a + i*h) ; s=s*h ; printf("Result =%20.12f\n", s) ; return 0; } |
f = @(x) 4/(1+x^2); a=0;b=1;s=0; n=10; %n=input('Enter n='); h=(b-a)/n; for i=0:1:n-1 s=s+f(a+i*h); end; s=s*h; fprintf('%f\n', s); |
|
|
/* Trapezoidal rule */ #include <stdio.h> double f(double x) {return 4.0/(1.0+x*x);} int main() { int i, n ; double a=0.0, b=1.0 , h, s=0.0, x; /* printf("Enter number of partitions = "); scanf("%d", &n) ; */ n=10; h = (b-a)/n ; for (i=1;i<=n-1;i++) s = s + f(a + i*h); s=h/2*(f(a)+f(b))+ h* s; printf("%20.12f\n", s) ; return 0; } |
f = @(x) 4/(1+x^2); a=0;b=1;s=0; n=10; %n=input('Enter n='); h=(b-a)/n; for i=1:1:n-1 s=s+f(a+i*h); end; s=h/2*(f(a)+f(b))+h*s; fprintf('%f\n', s); |
| (3) |
|
|
|
| (11) |
|
|
|
/* Simpson's rule */ #include <stdio.h> #include <math.h> double f(double x) {return 4.0/(1.0+x*x);} /* Note that the number of partitions is 2n, not n. */ int main() { int i, n ; double a=0.0, b=1.0 , h, s1=0.0, s2=0.0, s3=0.0, x; /* printf("Enter \"n\" (a half of the partitions) = "); scanf("%d", &n) ; */ n=5; h = (b-a)/(2.0*n) ; s1 = (f(a)+ f(b)); for (i=1; i<2*n; i=i+2) s2 = s2 + f(a + i*h); for (i=2; i<2*n; i=i+2) s3 = s3 + f(a + i*h); printf("The number of partitins is %d.\n", 2*n); printf("%20.12f\n", (h/3.0)*(s1+ 4.0*s2 + 2.0*s3)) ; return 0; } |
f = @(x) 4/(1+x^2); a=0;b=1;s1=0; s2=0;s3=0; n=5; %n=input('Enter n= (must be even)'); h=(b-a)/(2*n); s1=(f(a)+f(b)); for i=1:2:2*n-1 s2=s2+f(a+i*h); end; for i=2:2:2*n-1 s3=s3+f(a+i*h) ; end; s= (h/3)*(s1+4*s2+2*s3); fprintf('%f\n', s); |
|
|
|
|
|