usually we got same result(not exactly same, But nearly same) for following code (suggest X > 0 , Y > 0):
code 1 : fmod(X,Y)
code 2 : X - Y * trunc(X/Y)
But for some value, they will be very different.
test code:
int main()
{
cout << std::boolalpha;
cout << std::setprecision(20);
double X = 30.508474576271183309;
double Y = 6.1016949152542370172;
cout << "X: " << X << " Y:" << Y << '\n';
cout << "X/Y: " << X / Y << '\n';
cout << "X - trunc(X/Y)*Y: " << X - trunc(X / Y)*Y << '\n';
cout << "fmod(X,Y): " << fmod(X, Y) << '\n';
system("pause");
return 0;
}
result:
X: 30.508474576271183309 Y:6.1016949152542370172
X/Y: 5
X - trunc(X/Y)*Y: 0
fmod(X,Y): 6.1016949152542352408
env: VS2017 Win10
UPDATE 1 : this problem is not same as c++ fmod returns 0.2 for fmod(0.6,0.2)
if you set X to 0.6 and Y to 0.2, you will get same result for code 1 and code 2. But in this situation they will be different.
UPDATE 2 : I will use another way to describe the problem.
double X, X > 0, known
double Y, Y > 0, known
int quotient, quotient > 0, unknown
double remainder, remainder > 0, unknown
formula 1: X == Y * quotient + remainder
for known X,Y , if I want calculate quotient and remainder (and make sure they satisfied with the formula 1), in c++, usually we have two ways to do that:
Method 1: quotient = trunc(X/Y), remainder = fmod(X,Y);
Method 2: quotient = trunc(X/Y), remainder = X - Y * trunc(X/Y);
for Method 1, it will output quotient and remainder but they will not satisfied with the formula 1 (for specific X and Y).
UPDATE 3 : I meet this problem when doing ADS-B CPR local decoding. There is a step called "Calculate the latitude index j" as followed
if we strictly follow it and just replace mod with fmod in C++, then we will get wrong result for specific Lat_ref and dLat.