HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Newton's square root

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
newtonrootsquare

Problem

This is the code I wrote to compute the newton's square root of a number.

I aimed for extreme clarity over efficiency and I have put an abundant docstring at the start of the newton_sqrt function where I describe the main formula and explain all the parameters.

This function is not meant to be fast (standard library is 4x times faster and more accurate), I wrote just to learn some good math coding techniques in Python.

  • This was written in Python 3 but is fully compatible with Python 2.



  • I created constants for the error messages. Is that a good practice? Or should I just write the errors down verbatim when need occurs?



  • I chose n / 2 as my initial guess. Do you know a better initial guess?



  • Are all the option parameters that I am using necessary or should I delete some of them?



```
from __future__ import division
import time

def newton_sqrt(n,x0=None,tolerance=10 (-3),max_iter=15,epsilon=10 (-5)):
"""
This function computes the sqare root of a number
using Newton's method.
After chosing a starting approximate value for x runs:
x = x - f(x) / derivative_of_f(x)
After a given number of iterations or if the result is good enough
the programme will stop and return x.

Parameters:
Compulsory:
@ n: the number of which the square root must be taken.
Optional:
@ x0: the initial approximation of n.
@ tolerance: the maximum error permitted.
@ max_iter: the maximum number of iterations.
@ epsilon: a number so small that dividing by it would break
@ the programme, giving vastly inapproximate results.
"""
DIVISION_BY_TINY_DERIVATIVE_ERROR = """The derivative of f is {} and therefore under the {} limit chosen.
Dividing by it would give a result with a vast error."""
NOT_ENOUGH_ACCURACY_IN_ITER_ERROR = """Solution of {} accuracy for {} was not found in {} iterations"""

if x0 is None:
x0 = n / 2

f = lambda x: x ** 2 -

Solution

Looks good overall. Some suggestions:

-
The newton_sqrt is written in a quite generic manner. Unfortunately it may only calculate square roots - because lambdas are defined inside the function. I would rewrite it along the lines of

def newton_raphson(x, x0, func, derivative, governing_options):
    your code verbatim, except the lambda definitions 

def newton_sqrt(x, governing_options):
    return newton_raphson(x, x/2, lambda y: y*y - x, lambda y: 2*y, governing_options)


-
In any case, you most likely want to test for n > 0 and raise InvalidArgiment accordingly.

-
I am not sure about the epsilon. If an `abs(prime)

Code Snippets

def newton_raphson(x, x0, func, derivative, governing_options):
    your code verbatim, except the lambda definitions 

def newton_sqrt(x, governing_options):
    return newton_raphson(x, x/2, lambda y: y*y - x, lambda y: 2*y, governing_options)

Context

StackExchange Code Review Q#75279, answer score: 3

Revisions (0)

No revisions yet.