1

Saw a method of finding square roots from ancient Greece or Babylon.

Find the square root of x.

Assuming that a is an approximation to the square root of x, then the average of a and x / a is closer to the square root of x than a. Let a1 = (a + x / a) / 2 that a1 be a more accurate estimate of the square root of x than a. By analogy, more accurate square roots can be continuously obtained.

For example, to find the square root of 2, we first guess that it is 1.2 (any number greater than 1 and less than 2), and then continue to approximate

 1.2
(1.2 + 2/1.2)/2 = 1.43
(1.43 + 2/1.43)/2 = 1.414

code

 defmodule M do
  
  def sqrt(x, iter \\ 10)
  def sqrt(x, i) do
    a = (1+x)/2
    do_sqrt(x, a, i)
  end

  defp do_sqrt(_, a, 0), do: a
  defp do_sqrt(x, a, i) do
    a = (a + x/a)/2
    do_sqrt(x, a, i-1)
  end
end

have a test

image.png

appendix

Hero of Alexandria


Ljzn
399 声望102 粉丝

网络安全;函数式编程;数字货币;人工智能