Bob
Bob

Reputation: 27

Having strange output on the last list of values

I am iterating through a list which contains 4 lists. Below is the output that I get, I am wondering why I am getting this with the accuracy, for example, why is not the first just 1.00 as it is in other cases?

[[1]]
 [1] 1.00 0.96 0.84 0.74 0.66 0.56 0.48 0.36 0.26 0.16 0.06 0.00

[[2]]
 [1] 1.00 0.98 0.84 0.74 0.66 0.56 0.48 0.38 0.26 0.16 0.06 0.00

[[3]]
 [1] 1.00 0.94 0.84 0.74 0.66 0.56 0.48 0.36 0.26 0.16 0.06 0.00

[[4]]
 [1] 1.000000e+00 9.400000e-01 8.400000e-01 7.400000e-01 6.600000e-01 5.800000e-01 4.600000e-01 3.600000e-01 2.600000e-01 1.600000e-01 6.000000e-02 1.110223e-16

Upvotes: 0

Views: 2075

Answers (3)

IRTFM
IRTFM

Reputation: 263489

If you want floating point numbers displayed rounded to the second decimal digit then use:

lapply( mylist, round, digits=2)

This approach has the advantage that it returns numeric-mode values which a format() call would not and it can also be used with digit specifications that are "long" and could be an effective "zero-filter":

lapply(list(c(1,2), c(1.000000e+00, 9.400000e-01, 6.000000e-02, 1.110223e-16 )), round, 

digits=13)
[[1]]
[1] 1 2

[[2]]
[1] 1.00 0.94 0.06 0.00

Upvotes: 1

Dirk is no longer here
Dirk is no longer here

Reputation: 368629

As I commented when you first posted it as a follow-up comment on your previous question, this is more of a display issue. The last number is effectively zero:

R> identical(0, 1.1e-16)
[1] FALSE
R> all.equal(0, 1.1e-16)
[1] TRUE
R> 

While its binary representation is not zero, it evaluates to something close enough under most circumstances. So you could run a filter over your data and replace 'near-zeros' with zero, or you could debug the code and see how/why it comes out as non-zero.

Also see the R FAQ and general references on issues related to floating-point computations.

Upvotes: 2

NPE
NPE

Reputation: 500933

I am not sure of the exact algorithm R uses to chose the format. It is clear that a single format is used for all values in each list. It is also clear that the last list contains values of vastly different orders of magnitude: 1.000000e+00 and 1.110223e-16. I therefore think it's reasonable that R chooses to print the last list using scientific notation.

Upvotes: 0

Related Questions