Precise nth root
<p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>

<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. 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 <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>

<p>You can do a binary search on the answer. If you want to find the X that is equal to the kth root of N, you can do a binary search on X testing for each step of the binary search whether X^k equals N +- some small constant to avoid precision issues.</p>

<p>Here is the code:</p>

<pre><code>import math

N,K = map(float,raw_input().split()) # We want Kth root of N
lo = 0.0
hi = N
while 1:
    mid = (lo+hi)/2
    if math.fabs(mid**K-N) &lt; 1e-9: # mid^K is really close to N, consider mid^K == N
        print mid
        break
    elif mid**K &lt; N: lo = mid
    else: hi = mid
</code></pre>

<p>For (N,K) = (125,3) it prints 5.0, the correct answer. You can make it more precise by changing the 1e-9 constant, but there is a precision limit related to the float variables precision limit in Python</p>

python algorithm floating-point precision nth-root