[NTLUG:Discuss] The wrong computation example from the newsgroup
Greg Edwards
greg at nas-inet.com
Sun Mar 18 11:22:59 CST 2001
Steve Baker wrote:
>
> Chris Cox wrote:
> >
> > Here's the original problem... for those NTLUGgers who want a challenge.
>
> It's really not a challenge - it's just stupid. Anyone with an ounce of
> common sense and a couple of years programming experience can see what this
> is all about.
>
> > > If you've got a minute, and one of those 'bleeding edge' OSes, try compiling
> > > with no optimizations and running this for fun:
> > >
> > > int main(void)
> > > {
> > > int a = 60, b = 6, c = 10;
> > >
> > > printf("%d = %d\n", (int) (((60/6)*0.3) + (10*0.7)), (int) ((( a/b)*0.3) +
> > > ( c*0.7)));
> > >
> > > exit(1);
> > > }
>
> > > On all Linux distros, and only on Linux distros, ranging from an ancient
> > > Slackware setup to the latest Red Hat, I get 9=10. On everything else, I get
> > > 10=10.
>
> Well, the difference is that the first expression is optimised by the compiler
> and thus evaluated at compile time. The second expression has to be computed
> at runtime - although *some* compilers might figure out that they can compute
> it at runtime too.
>
> So - why is there a difference at all?
>
What seems like a very long time ago, a professor told me that if you
don't want bugs in your programs do not mix floating point and integer
arithmetic. We went through a very long discussion of what the problems
are in integer vs floating point from both the cpu (alu) and software
perspectives. This is not a problem that is limited to C compilers
either. In this particular case as Steve pointed out this is a compile
time (preprocessor) vs run time (math library) evaluation issue.
--
Greg Edwards
New Age Software, Inc.
http://www.nas-inet.com
More information about the Discuss
mailing list