c - What is wrong with my implementation for integration using Simpson's Rule -
i creating c program solving integrals using simpsons rule, wrote , runs, after giving program values returns me value definite integral of 0.0000. rechecked every line @ seems well, here's code problem appreciated
#include<stdio.h> #include<math.h> float ad(int a, int b, int n) { float f4, f2, z, v, q4=0, q2=0, d, m, fa, fb; int w=2, g=1, k=1, j=1; z=(b-a)/n; fa=6*pow(a,2)+16*pow(a,3); fb=6*pow(b,2)+16*pow(b,3); f4=6*pow(a+z*w,2)+16*pow(a+z*w,3); f2=6*pow(a+z*g,2)+16*pow(a+z*g,3); v=fa+fb; m=v*z; while(k<=n/2) { q4=q4+(z/3)*(4*f4); w=w+2; k++; } while(j<=(n-2)/2) { q2=q2+(z/3)*(2*f2); g=g+2; j++; } d=m+q4+q2; return d; } main() { int x, y, l; float o; printf("enter number x: "); scanf("%d", &x); printf("enter number y: "); scanf("%d", &y); printf("enter number: "); scanf("%d", &l); if(l%2!=0) { printf("the number odd!\n"); return 1; } o=ad(x, y, l); printf("the aprox integral es: %f\n", o); return 0; }
it gives me 2 errors:
--------------------configuration: mingw5 - cui debug, builder type: mingw-------------------- checking file dependency... compiling e:\anti simpson\ad.cpp... [warning] e:\anti simpson\ad.cpp:29: warning: converting `int' `float' [warning] e:\anti simpson\ad.cpp:50:2: warning: no newline @ end of file linking... complete make ad: 0 error(s), 2 warning(s) generated e:\anti simpson\ad.exe
you declared function return int, returning float, result is: float returning gets truncated, , int.
i'm guessing integrals had value between 0 , 1, function returned 0
just change int ad(int a, int b, int n)
float ad(int a, int b, int n)
edit: z=(b-a)/n;
a, b , n ints, won't fractional part in division. try z=(b-a)/(n * 1.0);
cast 1 of opreands float fractional part well
Comments
Post a Comment