Skip to content

Instantly share code, notes, and snippets.

@joepol
Last active March 4, 2020 17:08
Show Gist options
  • Save joepol/73a6d96d489bd79e0b35366885bf7e90 to your computer and use it in GitHub Desktop.
Save joepol/73a6d96d489bd79e0b35366885bf7e90 to your computer and use it in GitHub Desktop.
C++ floating point modulo that behaves like Matlab's mod function
inline double matlabMod(double q, double m)
{
if(m == 0)
return q;
double result = fmod(q, m);
return ((result >= 0 && m > 0) || (q <= 0 && m < 0)) ? result : (result + m);
}
/**
Tested with matlab for :
(54, 321) -> 54
(-50, 512) -> 462
(54, -152) -> -98
(-53, -500) -> -53
(-500, 300) -> 100
(-5000, 400) -> 200
(-1000, -360) -> -280
(500, 360) -> 140
(1000, 360) -> 280
(-1000, 360) -> 80
(-5051, 0) -> -5051
(512, 0) -> 512
(0, 52) -> 0
(0, -58) -> 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment