The title is quite self-explanatory, input is given double value, and I want to add/substract the smallest amount possible.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use
nextafter, which is available if your compiler implements C99’s math functions (i.e., C++11 and above). This function (and its various overloads) can be described as:It will move from
valuein the direction oftargetby the smallest possible amount (typically by tweaking the bit representation of the float). Ifvalueis already attarget, this does nothing.If
targetis greater thanvaluethis will incrementvalueby the smallest possible amount. Iftargetis less thanvaluethis will decrementvalueby the smallest possible amount.Common usage is to pass either
DBL_MAXorINFINITYas the target to increase the minimal amount (or, the negation of them to decrease the minimal amount).The choice between
DBL_MAXandINFINITYdepends on what you want to do at the boundary –nextafter(DBL_MAX, DBL_MAX) == DBL_MAX, butnextafter(DBL_MAX, INFINITY) == INFINITY.And yes, it’s poorly named. See also
nextafterandnexttoward: why this particular interface?.Even if your compiler doesn’t support it, it probably has an instrinsic for it. (MSVC has had
_nextaftersince 2005, for example. GCC probably implements it as standard.)If your compiler doesn’t support it but Boost is available to you, you can do this:
And if none of those work for you, you’ll just have to crack open the Boost header and copy it.