Home > front end >  Does `table` round numeric values?
Does `table` round numeric values?

Time:03-15

I have 120 vectors in a matrix points (120 x 2). I calculate their squared norms:

norms2 <- apply(points, 1L, crossprod)

I tabulate these squared norms:

> table(norms2)
norms2
0.410691055416468  1.62481505182984  2.37518494817016  3.58930894458353 
               30                30                30                30 

One sees that the squared norms take four possible values, 30 vectors for each value.

I extract the vectors which have the smallest squared norm:

> points[norms2 == min(norms2), ]
            [,1]       [,2]
[1,]  0.06698726 -0.6373412
[2,]  0.06698726  0.6373412
[3,] -0.06698726 -0.6373412
[4,] -0.06698726  0.6373412

Why do I get four vectors only, and not 30?

If I extract with an approximate equality, I get 30 vectors:

> dim(points[abs(norms2 - min(norms2)) < 0.001, ])
[1] 30  2

So what is the explanation? Does table round the values?

CodePudding user response:

Yes, table can round numeric input.

table() calls factor() which calls as.character(), and as.character() does some rounding:

x = sqrt(2)
print(x, digits = 22)
# [1] 1.414213562373095145475
as.character(x)
# [1] "1.4142135623731"

Here's a reproducible example:

x = c(pi, pi   1e-15)

x == pi
# [1]  TRUE FALSE

as.character(x)
# [1] "3.14159265358979" "3.14159265358979"

table(x)
# x
# 3.14159265358979 
#                2 
  •  Tags:  
  • r
  • Related