Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Simple fmod-Question

2 views
Skip to first unread message

Maic Schmidt

unread,
Nov 28, 2008, 12:47:06 PM11/28/08
to
Hi,

2 mod 0.2 should be 0, right?
But it isnt:

#include <math.h>
#include <stdio.h>

int main(void)
{
double x=2;
double y=0.2;
printf("%g mod %g = %g\n",x,y,fmod(x,y));
return 0;
}
=> 2 mod 0.2 = 0.2

Why not?

(Visual Studio 2005/2003 on XP/W2K)


Kai-Uwe Bux

unread,
Nov 28, 2008, 1:04:28 PM11/28/08
to
Maic Schmidt wrote:

> Hi,
>
> 2 mod 0.2 should be 0, right?
> But it isnt:
>
> #include <math.h>
> #include <stdio.h>
>
> int main(void)
> {
> double x=2;
> double y=0.2;
> printf("%g mod %g = %g\n",x,y,fmod(x,y));
> return 0;
> }
> => 2 mod 0.2 = 0.2
>
> Why not?

Maybe, because y is not exactly 0.2. As I see, you are printing results with
six significant digits. This may not be enough to see the differences.


Best

Kai-Uwe Bux

peter koch

unread,
Nov 28, 2008, 1:21:27 PM11/28/08
to
On 28 Nov., 18:47, "Maic Schmidt" <pri...@maicschmidt.de> wrote:
> Hi,
>
> 2 mod 0.2 should be 0, right?
Yes.

> But it isnt:
>
> #include <math.h>
> #include <stdio.h>
>
> int main(void)
> {
>   double x=2;
>   double y=0.2;
>   printf("%g mod %g = %g\n",x,y,fmod(x,y));
>   return 0;}
>
> => 2 mod 0.2 = 0.2
>
> Why not?

Because what you wrote as 0.2 isn't 0.2, but some number close to that
value. Just as 1/3 cant be represented precisely as a fraction,
neither can 0.2 (and 0.1 for that matter).

The result is accurate, but your perception about the representation
of floating point numbers is insufficient.

/Peter

Maic Schmidt

unread,
Nov 28, 2008, 1:23:56 PM11/28/08
to
Yes, you are right,
y was 0.20000000000000001

Think a have to look carefully for rounding errors with double...

I fear of checking them for 0, because my next task is a solver for
linear equations with gauss.

Thanks

Maic


"Kai-Uwe Bux" <jkher...@gmx.net> schrieb im Newsbeitrag
news:493032ac$0$17069$6e1e...@read.cnntp.org...

0 new messages