Is Root Algorithm
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p>

<pre><code>def isRoot(n, root):
   return not math.log(n, root)%1
</code></pre>

<p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p>

<pre><code>&gt;&gt;&gt; math.log(125,5)
3.0000000000000004
</code></pre>

<p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>

<p>You're relying on a floating point number being exactly equal to 0 (False) for your function to work. Generally speaking, you should avoid testing for equality when dealing with floating point numbers. Instead, it's better to set an acceptable tolerance level for the difference.</p>

<p>Try this instead:</p>

<pre><code>def isRoot(n, root, epsilon=1e-10):
    test = math.log(n, root)%1
    return abs(test - int(round(test))) &lt; epsilon
</code></pre>

python python-2.7 floating-point precision