I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!
Where could I obtain at least a guide how to program Nth root function that produces precise float
/Decimal
?
Such function that doesn't return 1
nor 0
for root(125, 1756482845)
(1st argument is the number, 2nd is the root depth (or something)).
EDIT: So, you were giving me this solution: n ** (1.0 / exp)
which I knew when I asked this question, but it just doesn't work for, for example, exp = 3
. You can't express 1/3
in terms of rational numbers, so 125 ** (1/3)
gives incorrect result 4.999999...
. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational exp
. If there isn't such function or algorithm, I will use this (n ** (1/exp)
).
nth roots are represented by the symbol n√. To find the nth root of a number we have to find that number, whose 'n' times multiplication by itself gives the number for which we have to find the nth root. Therefore the number that multiplied by itself n times is the nth root of the given number.
I would try the gmpy2 library.
>>> import gmpy2
>>> gmpy2.root(125,3)
mpfr('5.0')
>>>
gmpy2
uses the MPFR library to perform correctly rounded floating point operations. The default precision is 53 bits but that can be increased.
>>> gmpy2.root(1234567890123456789**11, 11)
mpfr('1.2345678901234568e+18') # Last digits are incorrect.
>>> gmpy2.get_context().precision=200
>>> gmpy2.root(1234567890123456789**11, 11)
mpfr('1234567890123456789.0',200)
>>>
Disclaimer: I maintain gmpy2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With