/* roots.c -- Newton's method to find polynomial roots Kincaid and Cheney Computer Exercise 3.5#5 Written September 25, 2012 for Math 701 by Eric Olson This code assumes all roots are simple roots. Input file format is n c0 c1 c2 c3 c4 ... cn where n is degree of polynomial and ck are real coefficients. End of data is indicated by n equal to -1. Version 1 to 2 changes: The input file format now allows complex coefficients. If n > 1000 then n - 1000 is the degree of the polynomial and the format for the coefficients is n c0.x c0.y c1.x c1.y ... cn.x cn.y */ #include #include #include #include #include #define FE_BAD (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW|FE_UNDERFLOW) /* Compile time constants are K maximum number of initial guesses N maximum number of iterations per guess L maximum degree of polynomial P number of pollishing iterations */ #define K 1000 #define N 1000 #define L 30 #define P 7 typedef long double complex Complex; typedef long double Real; typedef struct { int d; Complex c[L+1]; } polynomial; typedef struct { Complex y,dy; } jet; Complex guess(Real rho){ Real r=rho*random()/RAND_MAX; Real theta=2*M_PI*random()/RAND_MAX; return r*cexp(I*theta); } Real getrho(polynomial *p){ Real cmax=0.0; int i; for(i=0;id;i++){ Real r=cabsl(p->c[i]); if(r>cmax) cmax=r; } return cmax/cabsl(p->c[p->d])+1.0; } jet polyjet(polynomial *p,Complex z){ int j; jet r; r.y=p->c[p->d]; r.dy=0; for(j=1;j<=p->d;j++){ r.dy=r.dy*z+r.y; r.y=r.y*z+p->c[p->d-j]; } return r; } polynomial deflate(polynomial *p,Complex z){ polynomial q; int i,j; q.d=p->d-1; q.c[q.d]=p->c[p->d]; for(j=1;j<=q.d;j++) q.c[q.d-j]=q.c[p->d-j]*z+p->c[p->d-j]; return q; } Complex findroot(polynomial *p){ Complex z[N]; Real phi=(1.0+sqrt(5.0))/2.0; Real rhomin=pow(2.0,-54.0); Real rhomax=phi*getrho(p); int i,j,k; z[0]=guess(0.0); Real rho=rhomin; for(k=0;k>1]) return z[i]; if(fetestexcept(FE_BAD)){ feclearexcept(FE_BAD); break; } if(cabsl(z[i])>rhomax) break; } z[0]=guess(rho); rho*=phi; if(rho>rhomax) rho=rhomin; } printf("Failed to find a root!\n"); exit(4); } Complex pollish(polynomial *p,Complex z0){ Complex z=z0; int i; for(i=0;ir2) return 1; if(r11000) { p.d=i-1000; cflag=1; } else { p.d=i; cflag=0; } if(p.d>L) { puts("Memory exceeded!"); exit(1); } for(i=0;i<=p.d;i++){ Real x,y; if(scanf("%Lg",&x)!=1){ puts("Incomplete input data!"); exit(2); } if(cflag) { if(scanf("%Lg",&y)!=1){ puts("Incomplete complex number!"); exit(5); } } else y=0; p.c[i]=x+I*y; } for(i=0;i