1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#ifndef SQROOT_H
#define SQROOT_H
const double prec = 0.000001; // how close to the actual value should the root be extimated to.
const double nPrec = 2; // prec*10^n so that the findNearPrecRoots() function can be tuned.
// (rRoot1)^2 < rad < (rRoot2)^2;
// rRoot2 - rRoot1 = 1
// rRoot1 > 0; rRoot2 > 0
// Return true if number has real roots, false otherwise;
// PS. This is what I _expect_ to happen.
bool findRelRoots(long int rad, long int& rRoot1, long int& rRoot2){
if (0 <= rad){ // check to see if rad has real roots
rRoot1 = 0;
rRoot2 = 1;
if (rad <= 1){ // if rad is between 0 and 1, quit.
return true;
}
while (!((((rRoot1)*(rRoot1)) <= rad) && (rad <= ((rRoot2)*(rRoot2))))){
++(rRoot1); ++(rRoot2);
}
return true;
} else {return false;}
}
// this will approximate the root to within 1/100 of it's actual value.
// if it returns false, rRoot1 and rRoot2 will be equal, signifying that the
// root is the value of rRoot1 or 2 seening as they are both equal.
// if it returns true, it signifies that the root is between rRoot1 and rRoot2
// to within a hundreth of precision.
bool findNearPrecRoots(long int rad, double& rRoot1, double& rRoot2){
double temp;
if (rRoot1*rRoot1 == rad){
rRoot2 = rRoot1;
return false;
}
else if (rRoot2*rRoot2 == rad){
rRoot1 = rRoot2;
return false;
}else{
while (!(fabs(rRoot2 - rRoot1) <= prec*pow(10,nPrec))){
temp = (rRoot1+rRoot2)/2;
if ((rRoot1*rRoot1 < rad) && (rad < temp*temp)){
rRoot2 = temp;
}
else if ((temp*temp < rad) && (rad < rRoot2*rRoot2)){
rRoot1 = temp;
}else{
if (rRoot1*rRoot1 == rad){
rRoot2 = rRoot1;
return false;
}
else if ((rRoot2*rRoot2) == rad){
rRoot1 = rRoot2;
return false;
}
}
}
return true;
}
}
// will return the root of rad to within a 'prec' of precision.
double precRoot(long int rad, double rRoot1, double rRoot2){
double temp = rRoot1;
while (!((temp*temp == rad) || ((temp*temp < rad) && (rad < (temp+prec)*(temp+prec))))){ // Check to see if either temp^2 is equal to rad, or temp is within prec of rad
temp += prec;
if (temp == rRoot2){ // Something has gone horribly wrong
std::cout << "Stop Messing Around!";
return -1.0;
}
}
return temp;
}
double sqroot(long int rad){
long int rRoot1, rRoot2;
double d_rRootA, d_rRootB;
if (findRelRoots(rad,rRoot1,rRoot2)){
d_rRootA = rRoot1; d_rRootB = rRoot2;
if (findNearPrecRoots(rad, d_rRootA, d_rRootB)){
return precRoot(rad, d_rRootA, d_rRootB);
}else{
return d_rRootA;
}
}else{
std::cout << "[:*:] Please input a positive number";
return -1.0;
}
} // placeholder function for if included in header
#endif
|