//for generating random numbers
#include <cstdlib>
#include <ctime>
//for doing math
#include <cmath>
//for manipulating cout
#include <iomanip>
//for using cout
#include <iostream>
//for calculating machine epsilon
#include <limits>
using namespace std;
long double smartSubtraction(long double lvalue, long double rvalue)
{
long double result;
if (lvalue + rvalue > 1.0L)
{
//multiply by conjugate/conjugate, and simplify
result = (pow(lvalue,2) - pow(rvalue,2))/(lvalue + rvalue);
cout << "First if-statement executed..." << endl;
}
if (sqrt(lvalue) + sqrt(rvalue) < 1.0L)
{
//use conjugate decomposition to compute result
result = (sqrt(lvalue)-sqrt(rvalue))*(sqrt(lvalue)+sqrt(rvalue));
cout << "Second if-statement executed..." <<endl;
}
return result;
}
int main()
{
//set the precision to 19 decimal digits
cout << setprecision(19);
//seed the random number generator
srand(time(0));
//compute machineEpsilon
long double machineEpsilon = numeric_limits<long double>::epsilon();
cout << "machineEpsilon == " << machineEpsilon << "\n";
//create two random numbers in [1,101)
//the whole-number part should be in [1,100]
long double x = (long double)(rand() % 100 + 1), y = x;
//the fractional part should be [1,1000000] times machineEpsilon
x += machineEpsilon * (rand() * 999999 + 1);
y += machineEpsilon * (rand() * 999999 + 1);
//print both numbers
cout << "x == " << x << "\ny == " << y << endl;
//attempt subtraction two ways
//first way, straight subtraction
cout << "Using straight subtraction,\nx - y == " << (x-y) << endl;
//now use smartSubtraction() to subtract the two numbers
cout << "Using smartSubtraction()\nx - y == " << smartSubtraction(x,y) << endl;
return 0;
}