/* File: division.cpp * Author: Jason Charney (jrcharneyATgmailDOTcom) * Date: Mar 24, 2012 * Info: Demonstrate the division algorithm * LICENSE: MIT! * DON'T STEAL! I'll know if you've copied off of me! */ #include double p = 0.0000000001; // precision class DivideByZero { public: double divisor; DivideByZero(double x); }; DivideByZero::DivideByZero(double x) : divisor(x) {} // x = 1/D double reciprocal(double d){ if(d == 0.0) throw DivideByZero(d); double y, z; double x = 0.1; // initial guess do{ y=x*(2.0-d*x); // x_{i+1} = x_i * (2 - d * x_i) if(y == 0.0) break; // exit the loop if y = 0, x_i is the answer std::cout << y << "\t"; // show x_i z = y-x; // dx = x_{i+1} - x_i std::cout << z << "\n"; // show dx (optional, but I'm showing it anyway) if( z < 0.0) // if dx < 0 { x = x*0.1; // x_i = x_i * 0.1 z = 1.0; // tell the loop to keep going } else x = y; // else x_i = x_{i+1} }while(z > p); // do this so as long as dx > p return x; // return x_i }; // Q = N / D = N * x where x = 1/D double divide(double n, double d){ if(n == 0.0) return 0.0; if(d == 0.0) throw DivideByZero(d); return n * reciprocal(d); }; int main(){ try{ double n, d; std::cout << "Enter N: "; std::cin >> n; std::cout << "Enter D: "; std::cin >> d; std::cout << divide(n,d) << std::endl; // display the quotient } catch(DivideByZero divZero){ std::cerr << "ERROR: DIVBYZERO" << std::endl; return -1; } return 0; };