Tuesday, February 28, 2017

Square Root of Number using Newtons method in Scala




 package com.salpe.scala  
 object NewtonSquareRoot {  
  def main(args: Array[String]): Unit = {  
   print(squareRoot(3))  
  }  
  def squareRoot(x: Double): Double = {  
   def squareItr(guess: Double, x: Double): Double = {  
    def isConverged(guess: Double, x: Double): Boolean = {  
     abs(guess * guess - x) / x < 0.001  
    }  
    def improve(guess: Double, x: Double): Double = {  
     (guess + x / guess) / 2  
    }  
    if (isConverged(guess, x)) guess  
    else squareItr(improve(guess, x), x)  
   }  
   squareItr(1.0, x)  
  }  
  def abs(x: Double) = {  
   if (x < 0) -x else x  
  }  
 }  

No comments: