Given:
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
int main() {
// your code goes here
double h = .1;
double x = 1;
int nSteps = abs(x / h);
double rem = fmod(x, h);
cout<<"fmod output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"fmod output is almost near 0"<<endl;
rem = remainder(x,h);
cout<<"remainder output is "<<rem<<endl;
if(abs(rem)<std::numeric_limits<double>::epsilon())
cout<<"remainder output is almost near 0"<<endl;
return 0;
}
Given int(x/h) == 10
, I would have expected the fmod()
result to be near 0 but what i get is .0999999999. It is a significant difference. The result of remainder() still seem acceptable. Code could be tried at http://ideone.com/9wBlva
Why this significant difference for fmod() result?
fmod
andremainder
don't do the same thing, so different results are to be expected. – Aphisfloat
instead ofdouble
, the value comes out as expected Demo – Frontward.1
cannot be represented exactly in C++double
s (IEEE-754double
s, to be more precise), but I guess this output could need some more explanation. – Aphisusing namespace std;
!! . There is a reason why your question is tagged C++ , please think before tagging , so you dont spam other tags. Thankyou! – Paraboloidint(1/.1)
yields 10 instead of 9. – Aphis0.1
cannot be represented exactly in binary floating-point. The actual value ofh
is most likely0.1000000000000000055511151231257827021181583404541015625
, which can be represented exactly. – Barcot