创建一个用二分法求近似根的函数

root <- function(){
  x = as.numeric(readline("please input the number"))
  if (x<0){
    cat("The number you input is illegal"," ")
    root()
  }
  else{
    epsilon = 0.001
    numGusses = 1
    low = 0
    if(x>1){
      high = x
      
    }
    else{
      high = 1
    }
    ans = (high+low)/2
    while(abs(ans*ans-x)>epsilon){
      numGusses = numGusses+1
      if(ans*ans < x){
        low=ans
      }
      else{
        high = ans
      }
      ans = (high+low)/2.0
    }
    cat("numGuesses = ",numGusses," ")
    cat (ans , "is close to square root of", x ," ")
  }  
}

原文地址:https://www.cnblogs.com/wannaer/p/6918234.html