fork download
  1. //for generating random numbers
  2. #include <cstdlib>
  3. #include <ctime>
  4. //for doing math
  5. #include <cmath>
  6. //for manipulating cout
  7. #include <iomanip>
  8. //for using cout
  9. #include <iostream>
  10. //for calculating machine epsilon
  11. #include <limits>
  12.  
  13. using namespace std;
  14.  
  15. long double smartSubtraction(long double lvalue, long double rvalue)
  16. {
  17. long double result;
  18. if (lvalue + rvalue > 1.0L)
  19. {
  20. //multiply by conjugate/conjugate, and simplify
  21. result = (pow(lvalue,2) - pow(rvalue,2))/(lvalue + rvalue);
  22. cout << "First if-statement executed..." << endl;
  23. }
  24. if (sqrt(lvalue) + sqrt(rvalue) < 1.0L)
  25. {
  26. //use conjugate decomposition to compute result
  27. result = (sqrt(lvalue)-sqrt(rvalue))*(sqrt(lvalue)+sqrt(rvalue));
  28. cout << "Second if-statement executed..." <<endl;
  29. }
  30. return result;
  31. }
  32.  
  33. int main()
  34. {
  35. //set the precision to 19 decimal digits
  36. cout << setprecision(19);
  37. //seed the random number generator
  38. srand(time(0));
  39. //compute machineEpsilon
  40. long double machineEpsilon = numeric_limits<long double>::epsilon();
  41. cout << "machineEpsilon == " << machineEpsilon << "\n";
  42. //create two random numbers in [1,101)
  43. //the whole-number part should be in [1,100]
  44. long double x = (long double)(rand() % 100 + 1), y = x;
  45. //the fractional part should be [1,1000000] times machineEpsilon
  46. x += machineEpsilon * (rand() * 999999 + 1);
  47. y += machineEpsilon * (rand() * 999999 + 1);
  48. //print both numbers
  49. cout << "x == " << x << "\ny == " << y << endl;
  50. //attempt subtraction two ways
  51. //first way, straight subtraction
  52. cout << "Using straight subtraction,\nx - y == " << (x-y) << endl;
  53. //now use smartSubtraction() to subtract the two numbers
  54. cout << "Using smartSubtraction()\nx - y == " << smartSubtraction(x,y) << endl;
  55. return 0;
  56. }
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
machineEpsilon == 1.084202172485504434e-19
x == 28.00000000010069837
y == 28.00000000012091482
Using straight subtraction,
x - y == -2.021644830707547413e-11
First if-statement executed...
Using smartSubtraction()
x - y == -2.021644756354255173e-11