Skip to content

Instantly share code, notes, and snippets.

@zhukovgreen
Created October 11, 2021 14:23
Show Gist options
  • Save zhukovgreen/ff66099c5a81511040c3e4cd2963e667 to your computer and use it in GitHub Desktop.
Save zhukovgreen/ff66099c5a81511040c3e4cd2963e667 to your computer and use it in GitHub Desktop.
Implementation of the square root in scala
import org.scalatest.wordspec.AnyWordSpec
import scala.math.*
class test_different_samples extends AnyWordSpec {
/**Calculates square root of x*/
def square_root(x: Double, precision: Double = 0.01): Double = {
require(x >= 0)
def inner(min: Double, max: Double): Double = {
val guess = (min + max) / 2
if (abs(guess * guess - x) / x < precision) ||(x == 0) then guess
else {
guess * guess - x < 0 match {
case true => inner(guess, max)
case false => inner(min, guess)
}
}
}
inner(0, x)
}
"Iterative square root" should {
val res = square_root(64)
assert(res == 8)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment