Path: republic.btigate.com!news-xfer.netaxs.com!newsfeed.enteract.com!news.enteract.com!news.maxwell.syr.edu!newsfeed.internetmci.com!208.154.100.8!news.oz.net!bobc
From: bobc@oz.net (Bob Clark)
Newsgroups: comp.sys.hp48
Subject: Re: Calculating Square roots
Date: Wed, 15 Apr 1998 20:27:42 -0700
Organization: <personal>
Lines: 75
Message-ID: <bobc-1504982027420001@sense-sea-pm1-9.oz.net>
References: <6h0pmp$l87@dfw-ixnews8.ix.netcom.com>
NNTP-Posting-Host: sense-sea-pm1-9.oz.net
X-Newsreader: MT-NewsWatcher 2.3.5
X-Superfluous-Header: Yes
Xref: republic.btigate.com comp.sys.hp48:9404

In article <6h0pmp$l87@dfw-ixnews8.ix.netcom.com>, "Joel Johnson"
<joel48@writeme.com> wrote:

> How would one go about programmatically calculating the square root of a
> given number to 'n' decimal places?
> 
> I know that it is easier to use the ROM function on an HP, but was just
> wondering in general.

Hey Joel.

Do a web search for "Newton's Square Root Algorithm" or "Newton's Square
Root Loop".

You give the algorithm the number and an epsilon, where the maximum
difference between the result and the REAL square root is less than
epsilon.

N is the number.
s(i) is the current approximation to the square root.

assign s(0) = N/2

then

s(i) = ( N / s(i-1) + s(i-1) ) / 2

and stop iterating when

| Y - SQ(s(i)) | < epsilon

I've implemented it on the HP; since I don't have a cable handy, I'll try
typing it in. Enjoy, typos and all.

Pass in N and epsilon; it will return s(i) and i so you can see how many
iterations it took.

NewtonsSquareRoot

<<
  -> N eps
    <<
      N 2 / 0 -> s count
        <<
          WHILE N s SQ - ABS eps > REPEAT
            Y s / s + 2 / 's' STO count 1 + 'count' STO
          END
          s count
        >>
    >>
>>

Example: find the square root of 10 to 4 digits.

10 .0001 NewtonsSquareRoot

Result:

3.162277660044 in 4 iterations

Actual square root (using the HP48's square root key):

3.16227766017

In short, it converges very quickly. Of course, if you actually wanted to
use this to find square roots to insane accuracy, you'd need to have your
own way of storing ultra-high-resolution floating-point numbers. But it's
a fun exercise.

--Bob

-- 
Bob Clark              O-                                       Pax
bobc@oz.net                                 http://www.oz.net/~bobc
rambunctious@kagi.com     http://www.kagi.com/authors/rambunctious/