Created
October 12, 2020 07:01
-
-
Save alecthegeek/a7b335b645037bf70b94630b9b49f002 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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