In the example below, the application calculates the remainder of the floating point from dividing 953 by 0.1 using std::fmod
I expected with 953.0 / 0.1 == 9530 that std::fmod(953, 0.1) == 0
I get 0.1 - why is this so?
Please note that with std::remainder I get the correct result.
I.e:
std::fmod (953, 0.1) == 0.1
The difference between the two functions:
According to cppreference.com
std::fmod computes the following:
exactly the value x - n*y , where n - x/y , and its fractional part is truncated
std::remainder computes the following:
exactly the value x - n*y , where n is the integral value, the nearest exact value x/y
Given my inputs, I would expect both functions to have the same output. Why is this not so?
Exemplar example:
#include <iostream> #include <cmath> bool is_zero(double in) { return std::fabs(in) < 0.0000001; } int main() { double numerator = 953; double denominator = 0.1; double quotient = numerator / denominator; double fmod = std::fmod (numerator, denominator); double rem = std::remainder(numerator, denominator); if (is_zero(fmod)) fmod = 0; if (is_zero(rem)) rem = 0; std::cout << "quotient: " << quotient << ", fmod: " << fmod << ", rem: " << rem << std::endl; return 0; }
Output:
quotient: 9530, fmod: 0.1, rem: 0
source share