Skip to content

Instantly share code, notes, and snippets.

@dutc
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/1686573cbd49599610fb to your computer and use it in GitHub Desktop.
Save dutc/1686573cbd49599610fb to your computer and use it in GitHub Desktop.
Netwon's method (or any other iterative solving technique) with numpy
from numpy.random import randint
from numpy import sqrt
# Newton's method:
# `x' is input, `y' is iteratively refined answer
# solve for square root of x: y**2 = x
# f (y) = y^2 - x
# f'(y) = 2y
# y[1] = y[0] - f(y[0]) / f'(y[0])
xs = randint(1, 100, size=10).astype(float) # 10 numbers on [1,100)
ys = xs / 2 # first guess
unsolved = lambda xs, ys, accuracy = 0.01: abs(xs - ys ** 2) > accuracy
print '<{}>'.format(''.join('{:>4.0f}'.format(x) for x in xs))
us = unsolved(xs, ys)
while us.any():
ys[us] = ys[us] - (ys[us] ** 2 - xs[us])/(2 * ys[us])
us = unsolved(xs, ys)
print ' {} '.format(''.join(' {} '.format(' ' if u else '✓') for u in us))
for x, y, z, e in zip(xs, ys, sqrt(xs), abs(sqrt(xs) - ys)):
print '√{:2.0f} = {:>5.2f} = {:>5.2f} err: {:>6.4f}'.format(x, y, z, e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment