0

this works just fine:

t <- 2
repeat {
  print(t)
  t = t+2
  if (t == 8){
    break
  }
}

this does not:

t <- 0.1
repeat {
  print(t)
  t = t+0.1
  if (t == 1){
    break
  }
}

why?

pogibas
  • 27,303
  • 19
  • 84
  • 117
ivo
  • 77
  • 1
  • 5
  • Thanks for the link, I am new to R and the link does not help me to solve the problem. is there a straight forward solution to have a loop with decimals where break works? – ivo Jul 11 '18 at 08:56
  • try using `isTRUE(all.equal(...))` instead of `==` (as in the accepted answer ;p) – user20650 Jul 11 '18 at 09:29
  • @ivo The problem lies in floating point arithmetic (as well explained in the linked question). See that `0.1+0.2==0.3` returns `FALSE`. This means that if you keep adding `0.1`, due to floating point precision you don't end up exactly to 1 (and then the exit condition is never met). As for solving your issue: 1) you should never use equality conditions with floating point 2) you may use inequality (for instance `if (t<=1) break`). Keep in mind that the edge case might or might not included in the loop for the same reason (but at least you'll met the condition). – nicola Jul 11 '18 at 09:46
  • Thanks a lot, your answers helped me to understand and figure it out eventually. – ivo Jul 11 '18 at 10:20

0 Answers0