Skip to content

Instantly share code, notes, and snippets.

@tompng
Created August 24, 2025 13:53
Show Gist options
  • Select an option

  • Save tompng/6b79744a3ed3e4a9b5e537e1fffffe84 to your computer and use it in GitHub Desktop.

Select an option

Save tompng/6b79744a3ed3e4a9b5e537e1fffffe84 to your computer and use it in GitHub Desktop.
def sqrt(x, prec)
y = BigDecimal(Math.sqrt(x.to_f))
yinv = BigDecimal(1 / y.to_f)
(0..prec.bit_length).reverse_each do |i|
p = [[(prec >> i) + 2, BigDecimal.double_fig].max, prec].min
yinv = yinv.mult(BigDecimal(2).sub(y * yinv, p / 2), p / 2)
yinv = yinv.mult(BigDecimal(2).sub(y * yinv, p), p)
y = (y + x * yinv).div(2, p)
end
y
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment