Most viewed recipes tagged "math" and "maths" but not "distance"http://code.activestate.com/recipes/tags/math+maths-distance/views/2011-08-04T05:29:16-07:00ActiveState Code RecipesInteger square root function (Python) 2011-08-04T05:29:16-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577821-integer-square-root-function/ <p style="color: grey"> Python recipe 577821 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/isqrt/">isqrt</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/root/">root</a>, <a href="/recipes/tags/square/">square</a>). </p> <p>The <em>integer square root</em> function, or isqrt, is equivalent to floor(sqrt(x)) for non-negative x. For small x, the most convenient way to calculate isqrt is by calling int(x**0.5) or int(math.sqrt(x)), but if x is a large enough integer, the sqrt calculation overflows.</p> <p>You can calculate the isqrt without any floating point maths, using just pure integer maths, allowing the function to operate with numbers far larger than possible with floats:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; n = 1234567*(10**1000) &gt;&gt;&gt; n2 = n*n &gt;&gt;&gt; math.sqrt(n2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OverflowError: long int too large to convert to float &gt;&gt;&gt; isqrt(n2) == n True </code></pre> Floating point range (Python) 2010-02-24T07:12:55-08:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577068-floating-point-range/ <p style="color: grey"> Python recipe 577068 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/maths/">maths</a>, <a href="/recipes/tags/range/">range</a>). </p> <p>Generator that produces floats, equivalent to range for integers, minimising rounding errors by using only a single multiplication and addition for each number, and no divisions.</p> <p>This generator takes an optional argument controlling whether it produces numbers from the open, closed, or half-open interval.</p>