0

Possible Duplicate:
Why are these numbers not equal?

The following R code is part of a bigger function, and it keeps skipping the if statements and just doing the else statement at the end. Any suggestions? thanks

if(solv==0){
theta<-pi/2
} else if(solv==1){
theta<-0
}  else if(solv==-1) {
theta<-pi
}  else{
comb<-top/bottom

theta<-acos(comb)}
Community
  • 1
  • 1
  • Too few information. Try `print(solv)` before your `if` statement? – liuminzhao Dec 20 '12 at 03:05
  • What is letting you know that it is not working? Can you share that specific piece of information. I would put `dput(solve)` right before your if statement – Ricardo Saporta Dec 20 '12 at 03:12
  • 2
    See http://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal?lq=1. Try `if (isTRUE(all.equal(solve, 0)))` etc. – GSee Dec 20 '12 at 03:12
  • sorry that I didn't put more information, but the '(isTRUE(all.equal(solv, 0)))' did the trick. thanks – user1917509 Dec 20 '12 at 03:20

1 Answers1

0

The important question is, is solve an integer?

If not, then as @GSee alludes to in the comments to your question, the bug in your code is related to floating point errors

Try the following instead

# Set whichever tolerance is acceptable to you
tol <- 1e-16

if(isTRUE(all.equal(solv, 0, tolerance=tol))){
theta<-pi/2
} else if(isTRUE(all.equal(solv, 1, tolerance=tol))){
theta<-0
}  else if(isTRUE(all.equal(solv, -1, tolerance=tol))) {
theta<-pi
}  else{
comb<-top/bottom

theta<-acos(comb)}
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178