fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. template <typename T> double sgn(T val) {
  8. return double((T(0) < val) - (val < T(0)))/(val == val);
  9. }
  10. bool closeEnough(double LBD, double UBD, uint maxOrderDiff = 1, uint cutoffOrder = 1) {
  11. double sgn_LBD = sgn(LBD);
  12. double sgn_UBD = sgn(UBD);
  13. double cutoff = pow(10, cutoffOrder);
  14. double maxDiff = pow(10, maxOrderDiff);
  15. if(sgn_LBD == sgn_UBD) {
  16. bool test = -LBD<cutoff && UBD<cutoff;
  17. if(test) return test;
  18. return LBD<UBD && abs(UBD)<abs(LBD)*maxDiff;
  19. }
  20. else if(sgn_UBD > 0) {
  21. return -LBD<cutoff && UBD<cutoff;
  22. }
  23. // if none of the above matches LBD >= UBD or any of the two is NAN
  24. }
  25.  
  26.  
  27. bool closeEnoughLog(double LBD, double UBD) {
  28. double dist = 42;
  29. double sgn_LBD = sgn(LBD);
  30. double sgn_UBD = sgn(UBD);
  31. if(sgn_LBD == sgn_UBD) {
  32. if(LBD < UBD) { // central assumption!
  33. dist = max(log10(abs(UBD)), 0.0) - max(log10(abs(LBD)), 0.0);
  34. // We take max here because -10 < n < 10 is considered close enough!
  35. }
  36. }
  37. else if(sgn_UBD > 0) { // LBD <= 0
  38. dist = log10(-LBD) + log10(UBD); // can be negative but that's ok
  39. }
  40. // if none of the above matches LBD >= UBD or any of the two is NAN
  41. return (dist < 1);
  42. }
  43.  
  44. int main() {
  45. vector<double> LBD = {-INFINITY,-INFINITY,-100, -0.09, 0.09, NAN, -4, -2.4, 333, -40, -2.33};
  46. vector<double> UBD = {+INFINITY, NAN, 100, 1, 1, NAN, 0.02, 2.4, 231, 40, -0.023};
  47. vector<uint> desired = {0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1 };
  48. printf("%7s %7s %3s %6s %5s\n", "LBD", "UBD", "log", "simple", "check");
  49. for(auto i(0); i < desired.size(); ++i) {
  50. printf("%7.2f %7.2f %3d %6d %5d\n", LBD[i], UBD[i], closeEnoughLog(LBD[i], UBD[i]), closeEnough(LBD[i], UBD[i]), desired[i] );
  51. }
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
    LBD     UBD log simple check
   -inf     inf   0      0     0
   -inf     nan   0      0     0
-100.00  100.00   0      0     0
  -0.09    1.00   1      1     1
   0.09    1.00   1      1     1
    nan     nan   0      0     0
  -4.00    0.02   1      1     1
  -2.40    2.40   1      1     1
 333.00  231.00   0      0     0
 -40.00   40.00   0      0     0
  -2.33   -0.02   1      1     1