home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!uknet!comlab.ox.ac.uk!comlab.ox.ac.uk!imc
- From: imc@comlab.ox.ac.uk (Ian Collier)
- Newsgroups: comp.lang.rexx
- Subject: Square roots and things
- Message-ID: <2741.imc@uk.ac.ox.prg>
- Date: 19 Nov 92 18:27:23 GMT
- Sender: imc@comlab.ox.ac.uk (Ian Collier)
- Organization: Oxford University Computing Laboratory, UK
- Lines: 52
- X-Local-Date: Thursday, 19th November 1992 at 6:27pm GMT
- Originator: imc@msc5.comlab
-
- This is a follow-up to a long article I posted previously about calculating
- a square root. Sorry if this bores you...
-
- Anyway, my digit-by-digit method has been beaten fair-and-square by Newton's
- method, because I wrote a sqrt function which
-
- * makes a good estimate based on the mantissa and exponent of the argument
- * starts off at low precision and, after the low precision answer has been
- found, doubles the precision at each step.
-
- These together make a sqrt function which has the same complexity as a
- divide instruction. So, in cases where decimal divide is a native
- instruction (including any code written in REXX) this method will almost
- always be faster than my digit-by-digit method.
-
- Tests gave (in elapsed seconds):
-
- digits digit_method Newton's_method
- 10 0.59 0.13
- 50 3.68 0.72
- 100 8.63 2.19
- 200 26.29 7.87
- 400 89.26 30.31
- 800 304.14 125.23
-
- Here is the new sqrt() function:
-
- sqrt:procedure
- parse numeric d . /* or d=digits() */
- numeric form scientific
- parse arg x
- if x=0 then return 0
- parse value format(x,1,1,,0) with n +1 'E' exp /* error if x<0 */
- if exp='' then exp=0
- r=n/2||'E'||(exp+1)%2 /* divide both mantissa and exponent by 2 for initial
- estimate */
- d1=5
- numeric digits d1+2
- numeric fuzz 1
- do until r = r1 /* Get estimate accurate up to d1 digits */
- parse value r (x/r+r)/2 with r1 r
- end
- do while d1<d
- d1=min(d1+d1,d) /* Double up until required accuracy is reached */
- numeric digits d1+2
- parse value r (x/r+r)/2 with r1 r
- end
- numeric digits d
- return format(r)
-
- Ian Collier
- Ian.Collier@prg.ox.ac.uk | imc@ecs.ox.ac.uk
-