Skip to content

Instantly share code, notes, and snippets.

@alecthegeek
Created October 12, 2020 07:01
Show Gist options
  • Save alecthegeek/a7b335b645037bf70b94630b9b49f002 to your computer and use it in GitHub Desktop.
Save alecthegeek/a7b335b645037bf70b94630b9b49f002 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Find cube roots. In honour of Pandrosion of Alexandria on Ada Lovelace day 2020
# from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
# see also https://docs.python.org/3/tutorial/floatingpoint.html
def cubeRoot(a, epislon = 0.001):
''' Approximate cube roots using Halley's method
Examples
--------
>>> cubeRoot(27)[0]
3.0
>>> cubeRoot(19683, 0.00001)[0]
27.0
>>> cubeRoot(1)
(1.0, 3)
'''
from decimal import Decimal
n=0
result = a/2
while abs(result**3 - a) > epislon:
n += 1
cube = result**3
result *= ((cube+2*a)/(2*cube+a))
# print (f"cube of {a} is {result} after {n} iterations")
digits = abs(Decimal(repr(epislon)).as_tuple().exponent)
return round(result, digits), n
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment