[R] Unexpected result from binary greater than operator

Petr Pikal petr.pikal at precheza.cz
Tue Nov 1 17:29:07 CET 2005


Hi.
Easy. Regardless of OS and R version answer is

binary representation of fractions.

>    (4.2-4.1)>.1
[1] TRUE

but

>    (4.3-4.2)>.1
[1] FALSE

> print(4.3-4.2, digits=20)
[1] 0.099999999999999645

You can not expect precise results using not precise computers.

Use e.g. round

>    round(4.3-4.2)>.1
[1] FALSE

HTH
Petr


On 1 Nov 2005 at 9:15, chris.bodily at autolivasp.com wrote:

To:             	r-help at stat.math.ethz.ch
From:           	chris.bodily at autolivasp.com
Date sent:      	Tue, 1 Nov 2005 09:15:50 -0700
Subject:        	[R] Unexpected result from binary greater than operator

> Hi All,
> 
> I recently encountered results that I did not expect, exhibited by the
> following code snippet:
> 
> test <- function() {
>     minX <- 4.2
>     min0 <- 4.1
>     sigmaG <- 0.1
>     Diff <- minX-min0
>     print(c(Diff=Diff,sigmaG=sigmaG))
>     cat("is Diff > sigmaG?:", Diff > sigmaG,"\n")
>     cat("is (4.2 - 4.1) > 0.1?:",(4.2 - 4.1) > 0.1,"\n")
>     cat("is 0.1 > 0.1?:", 0.1>0.1,"\n")
> }
> 
> When I execute the above function I get the following:
> > test()
>   Diff sigmaG
>    0.1    0.1
> is Diff > sigmaG?: TRUE
> is (4.2 - 4.1) > 0.1?: TRUE
> is 0.1 > 0.1?: FALSE
> 
> Can someone please help me understand why R returns TRUE for (4.2 -
> 4.1) > 0.1 ?
> 
> Thanks so much,
> Chris
> 
> 
> I'm running the precompiled R-2.2.0 binary for Windows on WinXP Pro
> SP1.
> 
> >Sys.getlocale()
> "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United
> States.1252;LC_MONETARY=English_United
> States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
> 
> >version
>          _
> platform i386-pc-mingw32
> arch     i386
> os       mingw32
> system   i386, mingw32
> status
> major    2
> minor    2.0
> year     2005
> month    10
> day      06
> svn rev  35749
> language R
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

Petr Pikal
petr.pikal at precheza.cz




More information about the R-help mailing list