4

I wrote some code to check if a type has a modulo representation:

#include <iostream>
#include <limits>

using namespace std;

int main( )
{
    cout << "Whether float objects have a modulo representation: "
         << numeric_limits<float>::is_modulo << endl;
    cout << "Whether double objects have a modulo representation: "
         << numeric_limits<double>::is_modulo << endl;
}

Output:

Whether float objects have a modulo representation: 0
Whether double objects have a modulo representation: 0

But we can use fmod() (from <math.h>) to find modulo of float or double. So, why is is_modulo false if it is possible to find a modulo of a float or double?

Barry
  • 286,269
  • 29
  • 621
  • 977
SkrewEverything
  • 2,393
  • 1
  • 19
  • 50

3 Answers3

6

From cppreference

The value of std::numeric_limits<T>::is_modulo is true for all arithmetic types T that handle overflows with modulo arithmetic, that is, if the result of addition, subtraction, multiplication, or division of this type would fall outside the range [min(), max()], the value returned by such operation differs from the expected value by a multiple of max()-min()+1.

Overflow of floating point numbers is undefined behavior, therefore std::numeric_limits::is_modulo for float and double is false.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
3

This has nothing to do with fmod. Arbitrary operations on a floating-point value are irrelevant.

Whether one has "a modulo representation" is like how unsigned ints automatically wrap-around.

Neither floats nor doubles do that, and is_modulo is false accordingly.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

As described here:

The value of std::numeric_limits<T>::is_modulo is true for all arithmetic types T that handle overflows with modulo arithmetic, that is, if the result of addition, subtraction, multiplication, or division of this type would fall outside the range [min(), max()], the value returned by such operation differs from the expected value by a multiple of max()-min()+1.

so it does not say about 'finding modulo' but how a + b will behave. Floating point arithmetics do not overflows as integer arithmetics can.

Hcorg
  • 11,598
  • 3
  • 31
  • 36