Hacker News new | past | comments | ask | show | jobs | submit login

This is particularly sucky to solve in C and C++ because you don't get arbitrary precision literals.

    #include <boost/multiprecision/cpp_dec_float.hpp>
    #include <boost/lexical_cast.hpp>
    #include <iostream>

    using fl50 = boost::multiprecision::cpp_dec_float_50;

    int main() {
        auto a = boost::lexical_cast<fl50>("9999999999999999.7");
        auto b = boost::lexical_cast<fl50>("9999999999999998.5");
        std::cout << (a - b) << "\n";
    }
works

    int main() {
        fl50 a = 9999999999999999.7;
        fl50 b = 9999999999999998.5;
        std::cout << (a - b) << "\n";
    }
doesn't, even if you change fl50 out for a quad precision binary float type.



> Even user-defined literals in C++11 and later don't let you express custom floating point expressions

Note that in your code sample you're not actually using user-defined literals (https://en.cppreference.com/w/cpp/language/user_literal). This works (based on on your earlier code sample and adding user-defined literals):

    #include <boost/multiprecision/cpp_dec_float.hpp>
    #include <boost/lexical_cast.hpp>
    #include <iostream>
    using fl50 = boost::multiprecision::cpp_dec_float_50;
    fl50 operator"" _w(const char* s) { return boost::lexical_cast<fl50>(s); }
    int main() {
        fl50 a = 9999999999999999.7_w;
        fl50 b = 9999999999999998.5_w;
        std::cout << (a - b) << "\n";
    }


Thanks, it's nice to be wrong! For some reason I had it in my head that you couldn't get the token as a char const* for floating point expressions...




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: