Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precise nth root

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)).

like image 941
R.O.S.S Avatar asked Sep 30 '16 14:09

R.O.S.S


People also ask

What is the rule for nth root?

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.


1 Answers

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.

like image 185
casevh Avatar answered Oct 04 '22 18:10

casevh