I want to control the precision for a double during a comparison, and then come back to default precision, with C++.
I intend to use setPrecision() to set precision. What is then syntax, if any, to set precision back to default?
I am doing something like this
std::setPrecision(math.log10(m_FTOL));
I do some stuff, and I would like to come back to default double comparison right afterwards.
I modified like this, and I still have some errors
std::streamsize prec = std::ios_base::precision();
std::setprecision(cmath::log10(m_FTOL));
with cmath false at compilation, and std::ios_base also false at compilation. Could you help?
You can get the precision before you change it, with
std::ios_base::precisionand then use that to change it back later.You can see this in action with:
which outputs:
The code above shows two ways of setting the precision, first by calling
std::cout.precision (N)and second by using a stream manipulatorstd::setprecision(N).But you need to keep in mind that the precision is for outputting values via streams, it does not directly affect comparisons of the values themselves with code like:
In other words, even though the output may be
3.14159, the value itself is still the full3.141592653590(subject to normal floating point limitations, of course).If you want to do that, you’ll need to check if it’s close enough rather than equal, with code such as: