0

I am new to R and I am having difficulty with a simple recursion function. I initialize a variable, x to .1 and then make a call to a recursive function in which if x is not equal to the user-input number, it will add .1 to x and recursively call the function again. If x is greater than the input number, the function returns an error message.

I have tried setting x to a whole number, mainly 1 and then trying to evaluate the function. This process works, so I figure that there is an issue of adding decimal numbers to each other and then evaluating their equality with a whole number.

u<-function(a)
{
  #Initialize r
  x<-.1

  #Call to recursive method
  v(a, x)

}

#Recursive function
v<-function(a, x)
{
  #Check for current value of a and r
  print(a)
  print(x)

  if(a==x) {
    return("Yes")
  }

  else if(a < x) {
    return("Error!")
  }

  else{
    x<-x+.1
    v(a, x)
  }
}

When I set a to 1, I would expect the function to return "Yes" after recursing until x is equal to 1 as well. However, this is not the case. The function then recurses once more, setting x to 1.1 and returns the message "Error!".

1 Answers1

0

I think you are running into issues with floating point precision. If you use a function designed to check equality while accounting for floating point precision, like dplyr::near(), the function gives the expected result:

v<-function(a, x)
{
    #Check for current value of a and r
    print(a)
    print(x)

    if(dplyr::near(a, x)) {
        return("Yes")
    }

    else if(a < x) {
        return("Error!")
    }

    else{
        x<-x+.1
        v(a, x)
    }
}
Marius
  • 58,213
  • 16
  • 107
  • 105