Skip to content

Instantly share code, notes, and snippets.

@Lukas0025
Created August 6, 2021 12:34
Show Gist options
  • Save Lukas0025/b6aacb8d2a5d79d51d2f9ca7cd5af2ab to your computer and use it in GitHub Desktop.
Save Lukas0025/b6aacb8d2a5d79d51d2f9ca7cd5af2ab to your computer and use it in GitHub Desktop.
Calculate sqrt using newton iteration method
##
# Calculate sqrt using newton iteration method
# @autor Lukáš Plevač <lukas@plevac.eu>
# @date 6.8.2021
# Under CC0
#
import math
#
# Theory on: https://en.wikipedia.org/wiki/Newton%27s_method
#
##
# Calculate sqrt using newton iteration method
# @param x0 number for sqrt
# @param accuracy accuracy of output (default 0.001)
# @return sqrt(x0) with accuracy of accuracy
def newton_sqrt(x0, accuracy = 0.001):
x = x0 / 2 # initial estimate
while True:
cur_acc = x ** 2 - x0
if abs(cur_acc) <= accuracy:
break
else:
x = x - cur_acc / (2 * x) # calculation of a new x (refinement of the estimate)
return x
print(newton_sqrt(3))
print(math.sqrt(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment