Search code examples
c++floating-pointprecisionnumeric-limits

Largest floating point value that can be squared


I have a function that takes in an optional distance parameter dist, but my algorithm works with squared distances. If the user does not specify any value, I want dist to be as large a number as possible.

Result foo(double dist = std::sqrt(std::numeric_limits<double>::max())) const;

Is the code above safe, or will it blow up because of rounding errors? Would it be better to use something (even) uglier like

Result foo(double dist = std::sqrt(std::numeric_limits<double>::max() - 100)) const;

Solution

  • If you're careful, you can use std::numeric_limits<double>::infinity . It will do the right thing in comparisons and if you square it, it remains infinite.