Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <limits>
- #include <stdexcept>
- #include <cmath>
- bool close_enough(double a1, double a2, double threshold)
- {
- return a1 >= (a2 - threshold) && a1 <= (a2 + threshold);
- }
- double my_pow(double a, int b)
- {
- double result = 1.0;
- bool invert = false;
- if (b < 0) {
- invert = true;
- b = -b;
- }
- for (int n = 0; n < b; ++n) {
- result = result * a;
- }
- if (invert) {
- if (result != 0) {
- result = 1.0/result;
- } else {
- //throw std::overflow_error("divide by zero");
- result = std::numeric_limits<double>::infinity();
- }
- }
- return result;
- }
- void test_pow(double a, int b)
- {
- constexpr double thrs = 0.0001;
- constexpr int w = 10;
- double r1 = my_pow(a, b);
- double r2 = pow(a, b);
- bool ok = close_enough(r1, r2, thrs);
- std::cout << std::setw(w) << a
- << " ** "
- << std::setw(w) << std::left << b
- << " = "
- << std::right << std::setw(w)
- << std::setprecision(4) << r1
- << " ... "
- << (ok ? "ok!" : "NO.")
- << std::endl;
- if (!ok) {
- std::cerr << "pow(" << a << ", "
- << b << ") = " << pow(a, b)
- << std::endl;
- }
- }
- int main()
- {
- test_pow(0, 0);
- test_pow(1, 10);
- test_pow(2, 10);
- test_pow(2, -1);
- test_pow(2, -2);
- test_pow(2, -3);
- test_pow(-2, 1);
- test_pow(4, 1);
- test_pow(-2, 2);
- test_pow(-2, 3);
- test_pow(-2, -1);
- test_pow(-2, -2);
- test_pow(-2, -3);
- test_pow(10, -1);
- test_pow(11, -1);
- test_pow(12, -1);
- test_pow(10, -2);
- test_pow(12, -2);
- test_pow(10, -3);
- test_pow(100, -1);
- test_pow(100, -2);
- test_pow(100, -3);
- test_pow(100, -4);
- test_pow(-100, -4);
- test_pow(1000, 1);
- test_pow(0, -2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement