I know floating point numbers are strange, but I haven't come across this exact issue before. I have a vector of numbers in R. I see how many are bigger than zero, and I take the mean of this to get the proportion above zero. I assign the number to an object after rounding it. When I go to paste it, somehow the numbers come back. I would dput
the vector, but it is too long to do so, but here's the head
and str
:
> head(x)
[1] 0.1616631 0.2117250 0.1782197 0.1791657 0.2067048 0.2042075
> str(x)
num [1:4000] 0.162 0.212 0.178 0.179 0.207 ...
Now here's where I run into issues:
> y <- round(mean(x > 0) * 100, 1)
> y
[1] 99.7
> str(y)
num 99.7
> paste(100 - y, "is the inverse")
[1] "0.299999999999997 is the inverse"
But it doesn't behave the same if I don't subtract from 100:
> paste(y, "is it pasted")
[1] "99.7 is it pasted"
I know I could put round
right into the paste
command or use sprintf
, and I know how floats are represented in R, but I'm specifically wondering why it occurs for the former situation and not the latter? I cannot get a reproducible example, either, because I cannot get a randomly-generated vector to behave in the same way.