Skip to content

Instantly share code, notes, and snippets.

@theicfire
Created December 24, 2014 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theicfire/bb900403257349221be4 to your computer and use it in GitHub Desktop.
Save theicfire/bb900403257349221be4 to your computer and use it in GitHub Desktop.
# Find sqrt(2)
# Get a graph of y^2 - 2, find the 0. Use newtons's method.
import math
def iterate_root(start, n, p):
dx = .01
dy = ((start + dx) ** p) - (start ** p)
return start - ((start**p) - n)/(dy/dx)
def get_sqrt(n):
return reduce(lambda cur, y: iterate_root(cur, n, 2), [10] * 10)
def get_cube(n):
return reduce(lambda cur, y: iterate_root(cur, n, 3), [10] * 10)
def test_sqrt():
assert int(get_sqrt(2) * 1e5) == int(math.sqrt(2) * 1e5)
assert int(get_sqrt(3) * 1e5) == int(math.sqrt(3) * 1e5)
assert int(get_cube(2) * 1e5) == int(2 ** (1/3.0) * 1e5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment