Working with the set of real numbers

Chris Angelico rosuav at gmail.com
Thu Mar 6 08:16:24 EST 2014


On Thu, Mar 6, 2014 at 11:27 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> So my loop
>
>         while x ** 2 - y > x * eps:
>             x = (x + y/x) / 2
>
> and Chris' loop:
>
>     while abs(guess1-guess2) > epsilon:
>         guess1 = n/guess2
>         guess2 = (guess1 + guess2)/2
>
> and now your loop
>
>     while err > 1e-10:
>         err = n - guess * guess
>         guess += err/(2 * guess)
>
> are all performing the same basic algorithm. The only significant
> difference is that mine tests for a relative error condition where as
> the other two test for absolute error. This means that it will still
> converge to an answer with the correct precision even when the root is
> large e.g. sqrt(1e100). The other two are susceptible to infinite
> loops in this case.

This is one place where I find the REXX 'numeric fuzz' setting to be a
useful trick. The definition is that, whenever two numbers are
compared for equality, the 'numeric digits' setting is effectively
reduced by the fuzz for that comparison. So let's say we're
calculating to a precision of 100 digits ('numeric digits 100'). You
could then code the loop as "do until guess1=guess2", with a numeric
fuzz of, say, 2. That'll give you 98 digits of accuracy, *regardless
of scale*. It's like setting epsilon to "whatever would be 1e-98 if we
were working with numbers between 0 and 1", more or less. A sliding
epsilon.

ChrisA



More information about the Python-list mailing list