MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: strange bug?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg79183] Re: strange bug?
  • From: Steven Siew <siewsk at bp.com>
  • Date: Fri, 20 Jul 2007 03:32:00 -0400 (EDT)
  • References: <f7n4k9$24e$1@smc.vnet.net>

On Jul 19, 5:42 pm, "Jeremy Price" <cfga... at u.washington.edu> wrote:
> I think I've found a bug in mathematica 5.2,
>
> In[418]:=
> $Version
>
> Out[418]=
> 5.2 for Microsoft Windows (June 20, 2005)
>
> When I run, eg,
>
> In[416]:= IntegerPart[10*5.1]
>
> Out[416]= 51
>
> I get what I expect.  But when I run the same thing in a loop,
>
> For[n = 1, n < 20, n = n + .1,
>   Print[n, " ", IntegerPart[10*n]]
>   ]
>
> I get output like:
>
> >From In[415]:= 4.2 42
> >From In[415]:=4.3 43
> >From In[415]:=4.4 44
> >From In[415]:=4.5 45
> >From In[415]:=4.6 46
> >From In[415]:=4.7 47
> >From In[415]:=4.8 48
> >From In[415]:=4.9 48
> >From In[415]:=5. 49
> >From In[415]:=5.1 50
> >From In[415]:=5.2 51
>
> Any idea what's going on here or how to fix it?

That's easy.

in your loop
For[n = 1, n < 20, n = n + .1,

n is first defined as an integer but then it has a floating point
number .1 added to it.

This turn n from an integer to a floating point number.

But the floating point number must be represented in some fashion by
mathematica. However almost all computer languages represent floating
point number using an underlining binary representation.

Now .1 (aka 0.1) cannot be represented by binary floating point number
exactly. So most likely it is represented by something like this

0.099999999999999999

And if you add up 0.09999999999999 many many times, you are sure to
have a result which is slightly less than the correct result which you
were expecting.

That is the root cause of the problem you are experiencing.




  • Prev by Date: Re: Plot without Show
  • Next by Date: Re: Coding an inverse permutation
  • Previous by thread: Re: strange bug?
  • Next by thread: Re: strange bug?