From 36e20062708ef7a126ab1f3b8279c8f486573d93 Mon Sep 17 00:00:00 2001 From: Somaditya Basak Date: Sat, 19 Oct 2019 15:34:56 +0530 Subject: [PATCH 1/2] Added Newton-Raphson method, issue #455 --- Maths/Newton-Raphson/Newton-Raphson.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Maths/Newton-Raphson/Newton-Raphson.py diff --git a/Maths/Newton-Raphson/Newton-Raphson.py b/Maths/Newton-Raphson/Newton-Raphson.py new file mode 100644 index 00000000..07b23984 --- /dev/null +++ b/Maths/Newton-Raphson/Newton-Raphson.py @@ -0,0 +1,12 @@ +# Newton-Raphson for square root +# Find x such that x**2 - 1337 is within epsilon of 0.0001 +epsilon = 0.0001 +k = 1337.0 +guess = k/2.0 +counter = 1 +while abs(guess*guess - k) >= epsilon: + guess = guess - (((guess**2) - k)/(2*guess)) + print('#', counter, ' -> ', guess) + counter += 1 # track guesses + +print('Square root of', k, 'is about', guess) # should return ~ 36.565 From 81b91b9070deaa22546bf43872808cb242aef1e6 Mon Sep 17 00:00:00 2001 From: Somaditya Basak Date: Sat, 19 Oct 2019 15:52:09 +0530 Subject: [PATCH 2/2] added proper directory and conformed code convention --- Maths/Newton-Raphson/Newton-Raphson.py | 12 ---------- Maths/Newton-Raphson/Python/Newton-Raphson.py | 23 +++++++++++++++++++ 2 files changed, 23 insertions(+), 12 deletions(-) delete mode 100644 Maths/Newton-Raphson/Newton-Raphson.py create mode 100644 Maths/Newton-Raphson/Python/Newton-Raphson.py diff --git a/Maths/Newton-Raphson/Newton-Raphson.py b/Maths/Newton-Raphson/Newton-Raphson.py deleted file mode 100644 index 07b23984..00000000 --- a/Maths/Newton-Raphson/Newton-Raphson.py +++ /dev/null @@ -1,12 +0,0 @@ -# Newton-Raphson for square root -# Find x such that x**2 - 1337 is within epsilon of 0.0001 -epsilon = 0.0001 -k = 1337.0 -guess = k/2.0 -counter = 1 -while abs(guess*guess - k) >= epsilon: - guess = guess - (((guess**2) - k)/(2*guess)) - print('#', counter, ' -> ', guess) - counter += 1 # track guesses - -print('Square root of', k, 'is about', guess) # should return ~ 36.565 diff --git a/Maths/Newton-Raphson/Python/Newton-Raphson.py b/Maths/Newton-Raphson/Python/Newton-Raphson.py new file mode 100644 index 00000000..fdf6f5fb --- /dev/null +++ b/Maths/Newton-Raphson/Python/Newton-Raphson.py @@ -0,0 +1,23 @@ +# Using python3 +# Newton-Raphson for square root +# Find x such that x**2 - 1337 is within epsilon of 0.0001 +epsilon = 0.0001 +k = 1337.0 + + +def newton(n, eps): + guess = n/2.0 + count = 1 + + while abs(guess*guess - n) >= eps: + guess = guess - (((guess**2) - n)/(2*guess)) + print('Guess #', count, ' -> ', guess) + count += 1 # track no. of guesses + + return guess + + +if __name__ == '__main__': + test = 1337 + print('Square root of', test, 'is about', newton(test, 0.0001)) + # should return ~ 36.565 for test = 1337