c - EQUATION SOLVER absurd result despite correct algorithm -
#include<stdio.h> #include<math.h> #include<stdlib.h> void bisect(float *p,int n,int a); float value(float *p,int n,int a); int main() { int a,i; float *p; printf("enter degree of polynomial\n"); scanf("%d",&a); p=(float *) malloc(a*sizeof(float)); for(i=0;i<=a;i++) { printf("enter coefficient of x^%d\n",i); scanf("%f",p+i); } printf("%f\n",value(p,-2,a)); printf("%f\n",value(p,1,a)); printf("%f\n",value(p,0,a)); for(i=-100;i<100;i++) { if(value(p,i,a)*value(p,i+1,a)==0.000) { printf("%d\n",value(p,i+1,a)); if(value(p,i,a)==0&&value(p,i+1,a)==0.00) { printf("the roots %d,%d\n",i,i+1); } if(value(p,i+1,a)==0.0) { printf("the real root %d\n",i+1); i++; continue; } } if(value(p,i,a)*value(p,i+1,a)<0) { bisect(p,i,a); } } return 0; } float value(float *p,int n,int a) { float sum=0.0; int i; for(i=0;i<=a;i++) { sum=sum+*(p+i)*pow(n,i); } return sum; } void bisect(float *p,int n,int a) { float j,k,l; int i; j=n;k=n+1;l=(j+k)/2; for(i=0;i<50;i++) { if(value(p,j,a)*value(p,l,a)==0){break;} if(value(p,j,a)*value(p,l,a)<0) { j=j;k=l;l=(j+k)/2; } else if(value(p,l,a)*value(p,k,a)<0) { l=(l+k)/2;j=l; } } printf("the root of equation %f\n",l); }
i tried inserting print statements in main function, , found value function giving absurd results simple polynomials, roots correct polynomials wrong many. why roots correct if algorithm wrong?
there many problems in code:
- in
main
method,
printf("%d\n",value(p,-2,a));
compiler should give warning:
warning: format '%d' expects argument of type 'int', argument 2 has type 'double'
use %f
instead of %d
value()
returns float
.
- you not allocating enough space and casting return value of
malloc
. casting return value ofmalloc
should avoided sincemalloc
returnsvoid *
(which means needs no cast) , casting return value can conceal errors. can read more issue here.
p = (float *) malloc(a*sizeof(float));
to
p=malloc((a+1) * sizeof *p);
you comparing floating ponit number here:
if(value(p,i,a)==0&&value(p,i+1,a)==0.00)
don't this, read what every computer scientist should know floating-point arithmetic reason. can use 1 of (e.g nearlyequal()) functions purpose.
in method
bisect()
:j=j;k=l;l=(j+k)/2; // j = j, kidding?
Comments
Post a Comment