Skip to content

Implemented Square Root Algorithm #1687

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 15, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions maths/square_root.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import math


def fx(x: float, a: float) -> float:
return math.pow(x, 2) - a


def fx_derivative(x: float) -> float:
return 2 * x


def get_initial_point(a: float) -> float:
start = 2.0

while start <= a:
start = math.pow(start, 2)

return start


def square_root_iterative(
a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001
) -> float:
"""
Sqaure root is aproximated using Newtons method.
https://en.wikipedia.org/wiki/Newton%27s_method

>>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 for i in range(0, 500))
True

>>> square_root_iterative(-1)
Traceback (most recent call last):
...
ValueError: math domain error

>>> square_root_iterative(4)
2.0

>>> square_root_iterative(3.2)
1.788854381999832

>>> square_root_iterative(140)
11.832159566199232
"""

if a < 0:
raise ValueError("math domain error")

value = get_initial_point(a)

for i in range(max_iter):
prev_value = value
value = value - fx(value, a) / fx_derivative(value)
if abs(prev_value - value) < tolerance:
return value

return value


if __name__ == "__main__":
from doctest import testmod

testmod()