0

I had to use a similar code on some work I had to do and got this error. Basically I can´t understand why R says that the remainder of 234/6.5 is 6.5 when inside the loop but 0 (as it should be) when outside.

x=0
for (i in 1:100){
  x=x+3.6
  if (i==65){
    print(x)
    print(x%%6.5==0)
    print(x%%6.5)
    }
  
  if(x%%6.5==0){
    #print(i)
    break
  }
}  
x=234

x%%6.5==0

[1] 234
[1] FALSE
[1] 6.5
> x=234
> 
> x%%6.5==0
[1] TRUE

Any help is appreciated, and sorry for bad the english/explanation

goto
  • 3
  • 1
  • 1
    Perhaps `R`'s help can give some insight: "%% and x %/% y can be used for non-integer y, e.g. 1 %/% 0.2, but the results are subject to representation error and so may be platform-dependent. Because the IEC 60559 representation of 0.2 is a binary fraction slightly larger than 0.2, the answer to 1 %/% 0.2 should be 4 but most platforms give 5." – Martin Gal Dec 18 '20 at 21:03

1 Answers1

0

You could solve this by doing some rounding. In the examples below, if you round to 12 decimal places, you get the correct answer. If you round to 13 or more decimal places you get your original answer.

x=0
res <- NULL
for (i in 1:100){
  x=round(x+3.6, 12)
  if (i==65){
    print(x)
    print(x%%6.5==0)
    print(x%%6.5)
  }
  
  if(x%%6.5==0){
    #print(i)
    break
  }
}  

# [1] 234
# [1] TRUE
# [1] 0

x=0
for (i in 1:100){
  x=round(x+3.6, 13)
  if (i==65){
    print(x)
    print(x%%6.5==0)
    print(x%%6.5)
  }
  
  if(x%%6.5==0){
    #print(i)
    break
  }
}  

# [1] 234
# [1] FALSE
# [1] 6.5

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25