3
auto a{ 4.2 };
auto b{ 0.12 };
auto result = std::fmod(a, b);
if(result <= std::numeric_limits<double>::epsilon())
  result = 0; // <-- This line isn't triggered

In this example, 4.2 is actually equal to 4.2000000000000002 due to double imprecision.

Note that 4.2/0.12 = 35.

I would expect the output to be equal to std::numeric_limits<double>::epsilon(). Instead, result is equal to 1.5 * std::numeric_limits<double>::epsilon().

Where does this 1.5 multiplier come from?

2
  • 1
    Why would you expect the result to be equal to exactly epsilon? To verify why it is 1.5*epsilon, you can bring 4.2 and 0.12 into their binary form and then calculate the remainder.
    – chtz
    Aug 20, 2020 at 7:31
  • 3
    The size of the steps between the double numbers in [1, 2) is epsilon. The size of the steps between the double numbers in [4, 8), in which 4.2 lies, is 4*epsilon. The size of the steps between the double numbers in [.0625, .125), in which .12 lies, is epsilon/16. Let’s call these steps, epsilon/16, s. The double nearest 4.2 is apparently 24*s away from the nearest multiple of the double nearest .12. 24*s is 1.5*epsilon. That is where the 1.5 comes from. Aug 20, 2020 at 9:27

1 Answer 1

-2

The result of std::fmod may be expected to be accurate to within a ULP or so, but the machine epsilon is the ULP of 1, not of the result of any given operation.

4
  • 2
    fmod is one of the few floating point operations that always should be exact (assuming all inputs are finite and the divisor is not zero).
    – chtz
    Aug 20, 2020 at 7:32
  • @chtz Yes, I chose that wording because the operation being exact or not is not important to understand one cannot expect results to always be less than the machine epsilon.
    – Acorn
    Aug 20, 2020 at 16:26
  • To say a floating-point operation is exact is to say it has no error; the produced result is exactly the real-arithmetic result. So, yes, it is important to understand expectations about the result: The error will be less than the machine epsilon; it will be zero. Aug 20, 2020 at 20:05
  • Again, you are discussing guarantees on a particular operation and I am discussing the mistake of relating errors directly to the machine epsilon as if it was some kind of constant delta between the representable points.
    – Acorn
    Aug 21, 2020 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.