Advertisement
Guest User

Implements my_pow(), for int exp only.

a guest
Apr 29th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <limits>
  4. #include <stdexcept>
  5. #include <cmath>
  6.  
  7. bool close_enough(double a1, double a2, double threshold)
  8. {
  9.     return a1 >= (a2 - threshold) && a1 <= (a2 + threshold);
  10. }
  11.  
  12. double my_pow(double a, int b)
  13. {
  14.     double result = 1.0;
  15.     bool invert = false;
  16.     if (b < 0) {
  17.         invert = true;
  18.         b = -b;
  19.     }
  20.     for (int n = 0; n < b; ++n) {
  21.         result = result * a;
  22.     }
  23.     if (invert) {
  24.         if (result != 0) {
  25.             result = 1.0/result;
  26.         } else {
  27.             //throw std::overflow_error("divide by zero");
  28.             result = std::numeric_limits<double>::infinity();
  29.         }
  30.     }
  31.     return result;
  32. }
  33.  
  34. void test_pow(double a, int b)
  35. {
  36.     constexpr double thrs = 0.0001;
  37.     constexpr int w = 10;
  38.    
  39.     double r1 = my_pow(a, b);
  40.     double r2 = pow(a, b);
  41.     bool ok = close_enough(r1, r2, thrs);
  42.     std::cout << std::setw(w) << a
  43.               << " ** "
  44.               << std::setw(w) << std::left << b
  45.               << " = "
  46.               << std::right << std::setw(w)
  47.               << std::setprecision(4) << r1
  48.               << " ... "
  49.               << (ok ? "ok!" : "NO.")
  50.               << std::endl;
  51.     if (!ok) {
  52.         std::cerr << "pow(" << a << ", "
  53.                   << b << ") = " << pow(a, b)
  54.                   << std::endl;
  55.     }
  56. }
  57.  
  58. int main()
  59. {
  60.     test_pow(0, 0);
  61.     test_pow(1, 10);
  62.     test_pow(2, 10);
  63.     test_pow(2, -1);
  64.     test_pow(2, -2);
  65.     test_pow(2, -3);
  66.     test_pow(-2, 1);
  67.     test_pow(4, 1);
  68.     test_pow(-2, 2);
  69.     test_pow(-2, 3);
  70.     test_pow(-2, -1);
  71.     test_pow(-2, -2);
  72.     test_pow(-2, -3);
  73.     test_pow(10, -1);
  74.     test_pow(11, -1);
  75.     test_pow(12, -1);
  76.     test_pow(10, -2);
  77.     test_pow(12, -2);
  78.     test_pow(10, -3);
  79.     test_pow(100, -1);
  80.     test_pow(100, -2);
  81.     test_pow(100, -3);
  82.     test_pow(100, -4);
  83.     test_pow(-100, -4);
  84.     test_pow(1000, 1);
  85.     test_pow(0, -2);
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement