0

When running seq in specific instances in R, the output is incorrect, missing 0 by a very small precision.

Specifically:

Expected Output:

seq(from = -0.6, to = 0.7, by = 0.1)
[1] -0.6 -0.5 -0.4 -0.3 -0.2 -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7

R Output:

seq(from = -0.6, to = 0.7, by = 0.1)
[1] -6.000000e-01 -5.000000e-01 -4.000000e-01 -3.000000e-01 -2.000000e-01
[6] -1.000000e-01  1.110223e-16  1.000000e-01  2.000000e-01  3.000000e-01
[11]  4.000000e-01  5.000000e-01  6.000000e-01  7.000000e-01

This also seems to happen for seq(-0.7,0.7,0.1) as well, and I assume this behaviour happens for an unknown set of numbers as well.

Does anyone know why this is happening?

P.S. There is a solution to this issue, shown below:

seq(from = -0.6, to = 0.7, length.out = 14)
[1] -0.6 -0.5 -0.4 -0.3 -0.2 -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7

Or more generally:

seq(from = -0.6, to = 0.7, length.out = ((to + by) - from) / by)
[1] -0.6 -0.5 -0.4 -0.3 -0.2 -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7
Joni
  • 375
  • 1
  • 11
  • Also see [Why are these numbers not equal?](https://stackoverflow.com/q/9508518/4752675) – G5W Feb 12 '18 at 15:34
  • Not a duplicate exactly, but I think you are correct in saying floating point problem is the explanation, – Joni Feb 12 '18 at 15:39

0 Answers0