Scala Learning: Finding Square Root

I am renewing my learning in Scala and I have started the course Functional Programming Principles in Scala in Coursera. Here is some code which is taken from that course


 object SqrtCalculator extends App{  
  def abs(x: Double): Double = if(x < 0) - x else x  
  def sqrt (x: Double) : Double = {  
   def sqrtIterator(guess: Double): Double =  
    if (isGoodEnough(guess)) guess else sqrtIterator(improve(guess))  
   def isGoodEnough(guess: Double): Boolean =  
    abs(guess * guess - x) / x < 0.0001  
   def improve(guess: Double): Double =  
    (guess + x / guess) / 2  
   sqrtIterator(1.0)  
  }  
  println(sqrt(2))  
  println(sqrt(3))  
  println(sqrt(4))  
  println(sqrt(1e60))  
 }  

Output:
 1.4142156862745097  
 1.7320508100147274  
 2.0000000929222947  
 1.0000000031080746E30  
 Process finished with exit code 0  

Comments

  1. def isGoodEnough(guess: Double) = { abs(guess/x * guess/x - 1) < 0.0001 }

    This change in code doesnt give soln??

    ReplyDelete
    Replies
    1. it should not affect the solution. Those curly braces does not change the return value.

      Delete

Post a Comment

Popular posts from this blog

Deleting a hidden user in MAC

Problem Solving: Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node