Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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