3

Let a, b be real numbers with b != 0. I want to perform division with remainder of a by b. The result should be the unique real number r contained in [0, |b|) such that a = bc + r for some (unique) integer c.

std::fmod yields a similar result, but it allows r to be negative. For example, std::fmod(-.1, 1) == -.1, but I need a function which yields 0.9 for this example.

0xbadf00d
  • 17,405
  • 15
  • 67
  • 107

1 Answers1

2

You could build your own pretty easily:

double pos_fmod(double a, double b) {
    double mod_val = std::fmod(a, b);
    return mod_val >= 0 ? mod_val : b + mod_val;
}

Note that this assumes b > 0.

scohe001
  • 15,110
  • 2
  • 31
  • 51