Sqrt (square root) function
I'm going to concentrate on the Scala rather than the maths side, because that's my area.

The internal helper function doesn't need two parameters, since the value of x never changes; pushing x repeatedly onto the stack is a waste of time.  Also, better to use a case statement than a chain of if...else if...else - much less error prone.

def sqrt(x: Double): Double = {
  if (x &lt; 0) throw new IllegalArgumentException("negative numbers not allowed")
  val threshold = if (x &lt; 1) x / 1e15 else 1e-12
  def sqrtx(p: Double): Double = p match {
    case q if q == x / q =&gt; q // without this condition, non-termination with 1e50
    case q if Math.abs(q * q - x) &lt; threshold =&gt; {
      def diff1 = Math.abs(x - p * p)
      def diff2 = Math.abs(x - x / p * x / p)
      if (diff1 &lt; diff2) p else x / p
    }
    case _ =&gt; sqrtx((p + x / p) / 2)
  }
  sqrtx(x / 2)
}


I renamed the inner function sqrtx to avoid confusion about what it is doing.