0

I came across a strange thing in R programming. When I simulate a sequence and want to judge whether the element is less than 0.5,

t=(1:1440)/1440
x=(t[720]-t[648])/0.1
x
#output:[1] 0.5
x<1/2
#output:[1] TRUE
x=0.5
x<1/2
#output:[1] FALSE

The two results are completely opposite and obviously the second result is what I want. Can anybody help me?

1 Answers1

4

Floating point arithmetic is not exact in R, and the value you expect to be numerically exact to 0.5 may in fact be slightly more (or less). One possible workaround here would be to use rounding:

t <- (1:1440)/1440
x <- (t[720]-t[648]) / 0.1
round(x, 1) < 0.5
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360