Question

So here is a question I have mostly out of curiosity. I'm learning Pi with Paul Teetor's R Cookbook. I was playing around with some of the commands, when I came across this oddity:

> v
[1] 3.000000 3.140000 4.000000 3.141593 3.141593 3.141593 3.141593
> pi == v
[1] FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE

So checking what R considers pi to be,

> pi
[1] 3.141593

Apparently, R is giving me conflicting opinions on what pi is, or to show it more clearly I put the two into a matrix:

> v <- c(v, pi==v)
> mat <- matrix(v, 7, 2)
> mat
         [,1] [,2]
[1,] 3.000000    0
[2,] 3.140000    0
[3,] 4.000000    0
[4,] 3.141593    1
[5,] 3.141593    0
[6,] 3.141593    1
[7,] 3.141593    0

So apparently R considers pi to be 3.141593 on line 4, then not that on line 5, then back to 3.141593 on line 6, changing it's mind on 7 and so on. Does anyone know what is the cause of this interpreter's indecisiveness?

Was it helpful?

Solution

I don't get the same behaviour,

test <- function(digits, replications=10)
  c(representation = as.character(signif(pi, digits)), 
    equality = any(replicate(replications, pi == signif(pi, digits))))

t(sapply(1:16, test))

      representation     equality
 [1,] "3"                "FALSE" 
 [2,] "3.1"              "FALSE" 
 [3,] "3.14"             "FALSE" 
 [4,] "3.142"            "FALSE" 
 [5,] "3.1416"           "FALSE" 
 [6,] "3.14159"          "FALSE" 
 [7,] "3.141593"         "FALSE" 
 [8,] "3.1415927"        "FALSE" 
 [9,] "3.14159265"       "FALSE" 
[10,] "3.141592654"      "FALSE" 
[11,] "3.1415926536"     "FALSE" 
[12,] "3.14159265359"    "FALSE" 
[13,] "3.14159265359"    "FALSE" 
[14,] "3.1415926535898"  "FALSE" 
[15,] "3.14159265358979" "FALSE" 
[16,] "3.14159265358979" "TRUE"  

only returns TRUE for 16 digits, which is understandable because of the finite precision of doubles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top