首页 > 代码库 > 创建一个用二分法求近似根的函数

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

root <- function(){
  x = as.numeric(readline("please input the number"))
  if (x<0){
    cat("The number you input is illegal","\n")
    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,"\n")
    cat (ans , "is close to square root of", x ,"\n")
  }  
}

 

技术分享

 

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