/****************************************************************************** * This program demonstrates a significant digits rounding function. * * Copyright © 2017 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include #include #include #include std::locale utf8loc(std::locale(), new std::codecvt_utf8); using namespace Utils; using namespace std; double round_sig_dig(double value, int sigdigits) noexcept { if (value == 0.0) { return 0.0; } double const p = pow(10.0, sigdigits - int(floor(log10(abs(value)))) - 1); return floor(value * p + 0.5) / p; } int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); // Test with π for (int sd = 1; sd <= 16; ++sd) { wcout << fmt::format(L"π to {0:d} significant digits: {1:.16f}", sd, round_sig_dig(M_PI, sd)) << endl; } // Test with ℯ for (int sd = 1; sd <= 16; ++sd) { wcout << fmt::format(L"ℯ to {0:d} significant digits: {1:.16f}", sd, round_sig_dig(M_E, sd)) << endl; } // Test with 1/π for (int sd = 1; sd <= 16; ++sd) { wcout << fmt::format(L"1/π to {0:d} significant digits: {1:.16e}", sd, round_sig_dig(1.0 / M_PI, sd)) << endl; } // Test with 1e-6/e for (int sd = 1; sd <= 16; ++sd) { wcout << fmt::format(L"1e-6/e to {0:d} significant digits: {1:.16e}", sd, round_sig_dig(1e-6 / M_E, sd)) << endl; } return 0; }