Re: strange bug?
- To: mathgroup at smc.vnet.net
- Subject: [mg79160] Re: strange bug?
- From: David Bailey <dave at Remove_Thisdbailey.co.uk>
- Date: Fri, 20 Jul 2007 03:19:57 -0400 (EDT)
- References: <f7n4k9$24e$1@smc.vnet.net>
Jeremy Price 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? > Real numbers are not stored exactly - at least not once you start to do arithmetic on them. This is a fact of life, not a fault in the system. Normally this does not show, but in your case you probably ended up with n=4.99999999999999 (or similar) when you were expecting 5.1. At first sight this would seem not to be the case in your case, because you print out n, and it prints as 5.1, but don't be fooled. Mathematica rounds numbers to a smaller number of decimal digits in Standard Form - try printing InputForm[n]. First, I would recommend that you read about the topic of numbers of various precisions in Mathematica. The easiest way to fix the above problem is to take IntegerPart[10*n+0.000000001], but obviously the fix depends to some extent on what you want to do in your real problem. David Bailey http://www.dbaileyconsultancy.co.uk