sqrtWayne.frink

View or download sqrtWayne.frink in plain text format


/** This is an attempt to convert the algorithm of Prof. Wayne at Princeton
    for arbitrary precision sqrt (which only allows integer arguments) to a
    more generalized algorithm that allows floating-point arguments.

    https://introcs.cs.princeton.edu/java/92symbolic/ArbitraryPrecisionSqrt.java.html

    Thanks to Jeremy Roach for the research.
*/


sqrt[n, digits] :=
{
   // Intial estimate.  Find smallest power of 2 >= sqrt[n]
   // TODO:  Make this work with arbitrary precision?  Or faster?
   initial = 2.^ceil[ln[n] / ln[2] / 2]
   //   println["initial is $initial"]

   t = initial
   precision = 1

   origPrecision = getPrecision[]
   try
   {
      while (precision <= 2 * digits)
      {
         setPrecision[1 + 2 * precision]
         t = (n/t + t) / 2.
         precision = precision * 2
      }

      setPrecision[digits]
      return 1. t
   }
   finally
      setPrecision[origPrecision]
}


    


View or download sqrtWayne.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 17990 days, 1 hours, 38 minutes ago.