WExam 2 Cheat sheet

WExam 2 Cheat sheet - int i,j; //<- BUBBLE SORT...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int i,j; //<- BUBBLE SORT double temp1,temp2; for(i=0;i<n;i++) //n is the number of memory locations needing to be sorted { for(j=0;j<n-1;j++) { if(array[j]>array[j+1]) { temp1=array[j]; temp2=array[j+1]; array[j]=temp2; array[j+1]=temp1; } } } // finds the root to f(x) = ax^3 + bx^2 + cx + d const double tol=0.0001; // tolerance for convergence const int max_iter=100; // Number of maximum iterations allowed void bisection (double a, double b, double c, double d, double xl, double xr, double& root, int& iteration) { double xm; // local variables iteration=0; // setting number of iterations to zero do{ xm=(xl+xr)/2.; ++iteration; if(fx(a,b,c,d,xl)*fx(a,b,c,d,xm)<0) xr=xm; else xl=xm; cout<<"xm = "<<xm<<endl; }while ((fabs(fx(a,b,c,d,xm)) >= tol )&& (iteration < max_iter)); root=xm; } void substitution (double a, double b, double c, double d, double x0, double& root, int& iteration) { double x, xcalc; // local variables iteration=0; // setting number of iterations to zero x=x0; do{ ++iteration; xcalc=fxcalc(a,b,c,d,x); cout<<"xcalc "<<xcalc<<endl; x=xcalc; }while ((fabs(fx(a,b,c,d,xcalc)) >= tol )&& (iteration < max_iter)); root=xcalc; } void newton (double a, double b, double c, double d, double x0, double& root, int& iteration) { double xnew, xold; // local variables iteration=0; // setting number of iterations to zero xold=x0; do{ ++iteration; xnew = xold - fx(a,b,c,d,xold)/fprimex(a,b,c,d,xold); cout<<"xnew = "<<xnew<<endl; xold = xnew; }while ((fabs(fx(a,b,c,d,xnew)) >= tol )&& (iteration < max_iter)); root=xnew; } void secant (double a, double b, double c, double d, double x0, double x1, double& root, int& iteration) { double xnminus1, xnplus1, xn; // local variables iteration=0; // setting number of iterations to zero xnminus1=x0; xn=x1; do{ ++iteration; xnplus1 = xn - fx(a,b,c,d,xn)*(xn-xnminus1)/ (fx(a,b,c,d,xn)-fx(a,b,c,d,xnminus1)); cout<<"xnplus1 = "<<xnplus1<<endl; xnminus1 = xn; xn=xnplus1; }while ((fabs(fx(a,b,c,d,xnplus1)) >= tol )&& (iteration < max_iter)); root=xnplus1; } double fx(double a, double b, double c, double d, double x) //secant & bisection { return a*pow(x,3)+b*pow(x,2)+c*x+d; } double fxcalc(double a, double b, double c, double d, double x) //substitution { return pow((-b*x*x-c*x-d)/a,1./3.); } double fprimex(double a, double b, double c, double...
View Full Document

Page1 / 4

WExam 2 Cheat sheet - int i,j; //<- BUBBLE SORT...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online