From hb at stat.berkeley.edu  Tue Apr 18 18:35:11 2006
From: hb at stat.berkeley.edu (Henrik Bengtsson (max 7Mb))
Date: Tue, 18 Apr 2006 09:35:11 -0700
Subject: [Rd] seq() function accuracy inacceptable (PR#8779)
In-Reply-To: <20060418161910.E35EA1983E@slim.kubism.ku.dk>
References: <20060418161910.E35EA1983E@slim.kubism.ku.dk>
Message-ID: <59d7961d0604180935m4996feb4oeaf45faaa005b968@mail.gmail.com>

On 4/18/06, Johannes.Prix at wu-wien.ac.at <Johannes.Prix at wu-wien.ac.at> wrote:
> Full_Name: Johannes Prix
> Version: 2.1.1
> OS: WinXP, SuSE Linux
> Submission from: (NULL) (137.208.41.195)
>
>
>
> The seq-command produces unnescessary inaccurate results, which can be extremely
> annoying.  I absolutely do not see the nescessity of numerical garbage to appear
> in the following simple case.  E.g. try this:
>
> > seq ( 61.55 , 62.00 , by=0.01 ) - round ( seq ( 61.55 , 62.00 , by=0.01 ) ,
> digits=2 )
>
> Output looks like:
>
>  [1]  0.000000e+00 -7.105427e-15  0.000000e+00  0.000000e+00 -7.105427e-15
> -7.105427e-15  0.000000e+00  0.000000e+00
>  [9] -7.105427e-15  0.000000e+00  0.000000e+00  0.000000e+00 -7.105427e-15
> 0.000000e+00  0.000000e+00 -7.105427e-15
> [17] -7.105427e-15  0.000000e+00  0.000000e+00 -7.105427e-15  0.000000e+00
> 0.000000e+00 -7.105427e-15 -7.105427e-15
> [25]  0.000000e+00  0.000000e+00 -7.105427e-15  0.000000e+00  0.000000e+00
> -7.105427e-15 -7.105427e-15  0.000000e+00
> [33]  0.000000e+00 -7.105427e-15  0.000000e+00  0.000000e+00  0.000000e+00
> -7.105427e-15  0.000000e+00  0.000000e+00
> [41] -7.105427e-15 -7.105427e-15  0.000000e+00  0.000000e+00 -7.105427e-15
> 0.000000e+00
> >
>
> It is particularly dangerous to use such seq()-contructed lists (without
> rounding) when e.g. trying to find the first time a given number appears in the
> list and the number is given without numerical garbage.

Hmmm... I guess I'm the first on this one.  It is not garbage, it is
just the nearest number the computer can calculate given your
instructions. It has all to do about numerical precision, and
representation of numbers in a computer, e.g. 0.1 base 10 can not be
represented exactly in binary format.  For example, how do you write
1/3 (in base 10) on a piece of paper without using rational
representation?  In base 3 it is 0.1 sharp!  Look in the r-help
archive and you'll find tons of questions like yours and even more
answers.

For this reason, don't compare doubles using "==", that is very risky!
 Instead check if it is close enough, e.g. abs(x-y) < eps or
all.equal(x,y) or similar.

/Henrik


> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>


--
Henrik Bengtsson
Mobile: +46 708 909208 (+2h UTC)



[Rd] seq() function accuracy inacceptable (PR#8779)
Henrik Bengtsson (max 7Mb