This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages) (Learn how and when to remove this message)
|
Square root algorithms compute the non-negativesquare root of a positivereal number.Since all square roots ofnatural numbers, other than ofperfect squares, areirrational,[1]square roots can usually only be computed to some finite precision: thesealgorithms typically construct a series of increasingly accurateapproximations.
Most square root computation methods are iterative: after choosing a suitableinitial estimate of, aniterative refinement is performed until some termination criterion is met.One refinement scheme isHeron's method, a special case ofNewton's method.If division is much more costly than multiplication, it may be preferable to compute theinverse square root instead.
Other methods are available to compute the square rootdigit by digit, or usingTaylor series.Rational approximations of square roots may be calculated usingcontinued fraction expansions.
The method employed depends on the needed accuracy, and the available tools and computational power. The methods may be roughly classified as those suitable for mental calculation, those usually requiring at least paper and pencil, and those which are implemented as programs to be executed on a digital electronic computer or other computing device. Algorithms may take into account convergence (how many iterations are required to achieve a specified precision), computational complexity of individual operations (i.e. division) or iterations, and error propagation (the accuracy of the final result).
A few methods like paper-and-pencil synthetic division and series expansion, do not require a starting value. In some applications, aninteger square root is required, which is the square root rounded or truncated to the nearest integer (a modified procedure may be employed in this case).
Procedures for finding square roots (particularly thesquare root of 2) have been known since at least the period of ancient Babylon in the 17th century BCE.Babylonian mathematicians calculated the square root of 2 to threesexagesimal "digits" after the 1, but it is not known exactly how. They knew how to approximate a hypotenuse using(giving for example for the diagonal of a gate whose height is rods and whose width is rods) and they may have used a similar approach for finding the approximation of[2]
Heron's method from first century Egypt was the first ascertainable algorithm for computing square root.[3]
Modern analytic methods began to be developed after introduction of theArabic numeral system to western Europe in the early Renaissance.[4]
Today, nearly all computing devices have a fast and accurate square root function, either as a programminglanguage construct, a compiler intrinsic or library function, or as a hardware operator, based on one of the described procedures.
Many iterative square root algorithms require an initialseed value. The seed must be a non-zero positive number; it should be between 1 and, the number whose square root is desired, because the square root must be in that range. If the seed is far away from the root, the algorithm will require more iterations. If one initializes with (or), then approximately iterations will be wasted just getting the order of magnitude of the root. It is therefore useful to have a rough estimate, which may have limited accuracy but is easy to calculate. In general, the better the initial estimate, the faster the convergence. For Newton's method, a seed somewhat larger than the root will converge slightly faster than a seed somewhat smaller than the root.
In general, an estimate is pursuant to an arbitrary interval known to contain the root (such as). The estimate is a specific value of a functional approximation to over the interval. Obtaining a better estimate involves either obtaining tighter bounds on the interval, or finding a better functional approximation to. The latter usually means using a higher order polynomial in the approximation, though not all approximations are polynomial. Common methods of estimating include scalar, linear, hyperbolic and logarithmic. A decimal base is usually used for mental or paper-and-pencil estimating. A binary base is more suitable for computer estimates. In estimating, the exponent andmantissa are usually treated separately, as the number would be expressed in scientific notation.
Typically the number is expressed inscientific notation as where andn is an integer, and the range of possible square roots is where.
Scalar methods divide the range into intervals, and the estimate in each interval is represented by a single scalar number. If the range is considered as a single interval, the arithmetic mean (5.5) or geometric mean () times are plausible estimates. The absolute and relative error for these will differ. In general, a single scalar will be very inaccurate. Better estimates divide the range into two or more intervals, but scalar estimates have inherently low accuracy.
For two intervals, divided geometrically, the square root can be estimated as[Note 1]
This estimate has maximum absolute error of at, and maximum relative error of 100% at.
For factored as, the estimate is.
, an absolute error of 246 and relative error of almost 70%.
A better estimate, and the standard method used, is alinear approximation to the function over a small arc. If, as above, powers of the base are factored out of the numberS and the interval reduced to [1, 100], asecant line spanning the arc, or a tangent line somewhere along the arc may be used as the approximation, but a least-squares regression line intersecting the arc will be more accurate.
A least-squares regression line minimizes the average difference between the estimate and the value of the function. Its equation is. Reordering,. Rounding the coefficients for ease of computation,
That is the best estimateon average that can be achieved with a single piece linear approximation of the function in the interval [1, 100]. It has a maximum absolute error of 1.2 ata=100, and maximum relative error of 30% atS=1 and 10.[Note 2]
To divide by 10, subtract one from the exponent ofa, or figuratively move the decimal point one digit to the left. For this formulation, any additive constant 1 plus a small increment will make a satisfactory estimate so remembering the exact number isn't a burden. The approximation (rounded or not) using a single line spanning the range [1, 100] is less than one significant digit of precision; the relative error is greater than 1/22, so less than 2 bits of information are provided. The accuracy is severely limited because the range is two orders of magnitude, quite large for this kind of estimation.
A much better estimate can be obtained by a piece-wise linear approximation: multiple line segments, each approximating some subarc of the original. The more line segments used, the better the approximation. The most common way is to use tangent lines; the critical choices are how to divide the arc and where to place the tangent points. An efficacious way to divide the arc fromy = 1 toy = 100 is geometrically: for two intervals, the bounds of the intervals are the square root of the bounds of the original interval, 1×100, i.e.[1,2√100] and[2√100,100]. For three intervals, the bounds are the cube roots of 100:[1,3√100], [3√100,(3√100)2], and[(3√100)2,100], etc. For two intervals,2√100 = 10, a very convenient number. Tangent lines are easy to derive, and are located at and. Their equations are: and. Inverting, the square roots are: and. Thus for:
The maximum absolute errors occur at the high points of the intervals, ata=10 and 100, and are 0.54 and 1.7 respectively. The maximum relative errors are at the endpoints of the intervals, ata=1, 10 and 100, and are 17% in both cases. 17% or 0.17 is larger than 1/10, so the method yields less than a decimal digit of accuracy.
In some cases, hyperbolic estimates may be efficacious, because a hyperbola is also a convex curve and may lie along an arc ofy =x2 better than a line. Hyperbolic estimates are more computationally complex, because they necessarily require a floating division. A near-optimal hyperbolic approximation tox2 on the interval [1, 100] is. Transposing, the square root is. Thus for:
The division need be accurate to only one decimal digit, because the estimate overall is only that accurate, and can be done mentally. This hyperbolic estimate is better on average than scalar or linear estimates. It has maximum absolute error of 1.58 ata = 100 and maximum relative error ata = 10, where the estimate of 3.67 is 16.0% higher than the root of 3.16. If instead one performed Newton-Raphson iterations beginning with an estimate of 10, it would take two iterations to get to 3.66, matching the hyperbolic estimate. For a more typical case like 75, the hyperbolic estimate of 8.00 is only 7.6% low, and 5 Newton-Raphson iterations starting at 75 would be required to obtain a more accurate result.
A method analogous to piece-wise linear approximation but using only arithmetic instead of algebraic equations, uses the multiplication tables in reverse: the square root of a number between 1 and 100 is between 1 and 10, so if we know 25 is a perfect square (5 × 5), and 36 is a perfect square (6 × 6), then the square root of a number greater than or equal to 25 but less than 36, begins with a 5. Similarly for numbers between other squares. This method will yield a correct first digit, but it is not accurate to one digit: the first digit of the square root of 35 for example, is 5, but the square root of 35 is almost 6.
A better way is to the divide the range into intervals halfway between the squares. So any number between 25 and halfway to 36, which is 30.5, estimate 5; any number greater than 30.5 up to 36, estimate 6.[Note 3] The procedure only requires a little arithmetic to find a boundary number in the middle of two products from the multiplication table. Here is a reference table of those boundaries:
| a | nearest square | est. |
|---|---|---|
| 1 | ||
| 1 (= 12) | 1 | |
| 2.5 | ||
| 4 (= 22) | 2 | |
| 6.5 | ||
| 9 (= 32) | 3 | |
| 12.5 | ||
| 16 (= 42) | 4 | |
| 20.5 | ||
| 25 (= 52) | 5 | |
| 30.5 | ||
| 36 (= 62) | 6 | |
| 42.5 | ||
| 49 (= 72) | 7 | |
| 56.5 | ||
| 64 (= 82) | 8 | |
| 72.5 | ||
| 81 (= 92) | 9 | |
| 90.5 | ||
| 100 (= 102) | 10 | |
| 100 | ||
The final operation is to multiply the estimatek by the power of ten divided by 2, so for,
The method implicitly yields one significant digit of accuracy, since it rounds to the best first digit.
The method can be extended 3 significant digits in most cases, by interpolating between the nearest squares bounding the operand. If, then is approximately k plus a fraction, the difference betweena andk2 divided by the difference between the two squares: where
The final operation, as above, is to multiply the result by the power of ten divided by 2;
k is a decimal digit andR is a fraction that must be converted to decimal. It usually has only a single digit in the numerator, and one or two digits in the denominator, so the conversion to decimal can be done mentally.
find the square root of 75.
, soa is 75 andn is 0. From the multiplication tables, the square root of the mantissa must be 8 pointsomething becausea is between 8×8 = 64 and 9×9 = 81, sok is 8;something is the decimal representation ofR. The fractionR = 75 −k2 = 11, the numerator, and81 −k2 = 17, the denominator. 11/17 is a little less than 12/18 = 2/3 = .67, so guess .66 (it's okay to guess here, the error is very small). The final estimate is8 + .66 = 8.66.
√75 to three significant digits is 8.66, so the estimate is good to 3 significant digits. Not all such estimates using this method will be so accurate, but they will be close.
When working in thebinary numeral system (as computers do internally), by expressingS as where, the square root can be estimated as
which is the least-squares regression line to 3 significant digit coefficients. has maximum absolute error of 0.0408 at, and maximum relative error of 3.0% at. A computationally convenient rounded estimate (because the coefficients are powers of 2) is:
which has maximum absolute error of 0.086 at 2 and maximum relative error of 6.1% ata = 0.5 anda = 2.0.
For the binary approximation gives, so the estimate has an absolute error of 19 and relative error of 5.3%. The relative error is a little less than 1/24, so the estimate is good to 4+ bits.
An estimate fora good to 8 bits can be obtained by table lookup on the high 8 bits ofa, remembering that the high bit is implicit in most floating point representations, and the bottom bit of the 8 should be rounded. The table is 256 bytes of precomputed 8-bit square root values. For example, for the index 111011012 representing 1.851562510, the entry is 101011102 representing 1.35937510, the square root of 1.851562510 to 8 bit precision (2+ decimal digits).
The first explicitalgorithm for approximating is known asHeron's method, after the first-centuryGreek mathematicianHero of Alexandria who described the method in hisAD 60 workMetrica.[3] This method is also called theBabylonian method (not to be confused with theBabylonian method for approximating hypotenuses), although there is no evidence that the method was known toBabylonians.
Given a positive real number, letx0 > 0 be any positiveinitial estimate.Heron's method consists in iteratively computinguntil the desired accuracy is achieved.The sequence defined by this equation converges to
This is equivalent to usingNewton's method to solve. This algorithm isquadratically convergent: the number of correct digits of roughly doubles with each iteration.[5]
The basic idea is that if is an overestimate to the square root of a positive real number then will be an underestimate, and vice versa, so the average of these two numbers may reasonably be expected to provide a better approximation. (Theformal proof of that assertion depends on theinequality of arithmetic and geometric means that shows this average is always an overestimate of the square root, as noted in the article onsquare roots, thus assuring convergence.)
More precisely, if is our initial guess of and is the error in our estimate such that then we can expand the binomial as: and solve for the error term
Therefore, we can compensate for the error and update our old estimate as Since the computed error was not exact, this is not the actual answer, but becomes our new guess to use in the next round of correction. The process of updating is iterated until desired accuracy is obtained.
This algorithm works equally well in thep-adic numbers, but cannot be used to identify real square roots withp-adic square roots; one can, for example, construct a sequence of rational numbers by this method that converges to+3 in the reals, but to−3 in the 2-adics.
fromdecimalimportDecimal,localcontext,getcontextNumberType=int|float|Decimaldefsqrt_Heron(s:NumberType,precision:int|None=None,guess:NumberType|None=None)->Decimal:""" Compute sqrt(s) using the Heron-Newton method with arbitrary precision. :param s: Non-negative number whose square root to compute. :param precision: Number of significant digits. Defaults to the current decimal context. Minimum supported precision is 2. (Precision = 1 is disallowed to avoid rounding anomalies.) :param guess: Initial guess. Defaults to s / 2. :return: Approximation of sqrt(s) rounded to the specified precision. """ifs==0:returnDecimal(0)s=Decimal(s)ifs<0:raiseValueError("sqrt(s) is not defined for negative numbers.")ifprecisionisNone:precision=getcontext().prec# use current global context if not specified# Silently enforce minimum precisionifprecision<2:precision=2ifguessisNone:guess=Decimal(s/2)guard=25# temporary extra digits for internal stabilitymax_iter=10_000# Local context: isolate precision changeswithlocalcontext()asctx:ctx.prec=precision+guardguess=(guess+s/guess)/2for_inrange(max_iter):next_guess=(guess+s/guess)/2# Stop when improvement is small enoughifguess-next_guess<Decimal(f"1e-{precision}"):breakguess=next_guesselse:raiseArithmeticError(f"Heron method did not converge within{max_iter} iterations")# Round to target precision (getting rid of guard)ctx.prec=precisionreturn+next_guess
The following example demonstrates the execution of thesqrt_Heron function with various inputs
print(f"1){sqrt_Heron(125348,precision=7,guess=600)}")print(f"2){sqrt_Heron(Decimal('3.1415926535897932384626433832795028841971693993'))}")print(f"3){sqrt_Heron(2,1_000_157)}")print(f"4){sqrt_Heron(2,10_000_005,1.414)}")print(f"5){sqrt_Heron(2,100_000_000,1)}")
This produces the following output:
1) 354.04522) 1.7724538509055160272981674833) 1.4142135623730950488016887242 ... 2697320257318491414938800048567428924) 1.4142135623730950488016887242 ... ... 8724805080541235727278721315897142625) 1.4142135623730950488016887242 ... ... ... 023678977744844723443287604232894971
Ad 1)
The computation of for to seven significant figures takes the following course:
Therefore to seven significant figures (rounded).
Ad 2) Computation (in 6 iteration steps) of to default precision.[Note 5]
Ad 3) Computation (in 22 iteration steps) of to 1,000,157 digits.[6]
Ad 4) Computation (in 23 iteration steps) of to 10,000,005 digits.[7]
Ad 5) Computation (in 28 iteration steps) of to 100 million digits.[citation needed]
It appears that for reasonable initial guesses not many iterations are needed.
Heron's method has the following property:
In plain words:Once the iteration produces a value greater than (which happens immediately if, or after one step if), every following estimate remains above but gets smaller each time — so the sequence “slides down” toward and converges.
In line 41 of the program,guess is set to a value. Then in line 46 of the code, cannot be negative.
By using the difference between successive estimates,
as the stopping criterion, the method ensures that the sequence of approximations is converging toward the true value. When the successive differences become sufficiently small, the given goal is reached. The key insight is that theabsolute error
is directly related to the size of the successive improvement. Specifically, for iterative methods that converge linearly or quadratically, there exists a constant such that
This relationship implies that as decreases, the absolute error also becomes smaller. Therefore, stopping the iteration when falls below a given threshold ensures that the actual error is within at most that threshold.

Suppose that Then for any natural number Let therelative error in be defined byand thus
Then it can be shown that
And thus thatand consequently that convergence is assured, andquadratic.
If using the rough estimate above with the Babylonian method, then the least accurate cases in ascending order are as follows:
Thus in any case,
Rounding errors will slow the convergence. It is recommended to keep at least one extra digit beyond the desired accuracy of the being calculated, to avoid significant round-off error.
When in the program above the estimates — the highlighted lines 41 and 43 —
guess=(guess+s/guess)/2# ...next_guess=(guess+s/guess)/2
are replaced by
guess*=(guess*guess+3*s)/(3*guess*guess+s)# ...next_guess=guess*(guess*guess+3*s)/(3*guess*guess+s)
the functionsqrt_Heron is transformed into an implementation ofHalley's method, where
As in Halley's method the estimates do not always move in one direction, line 46 will become
ifabs(guess-next_guess)<Decimal(f"1e-{precision}"):Halley's method converges faster —therate of convergence to the root is cubic, which is better thanquadratic— iteration for iteration, but involves five multiplications per iteration (counting division as three multiplications). The five example computations are completed in 4, respectively 4, 14, 15, and 19 iteration steps. By contrast Heron's method only needs one division i.e. three multiplications, so Heron's method is slightly better in the long run.
This method for finding an approximation to a square root was described in an AncientIndian manuscript, called theBakhshali manuscript. It is algebraically equivalent to two iterations of Heron's method and thus quartically convergent, meaning that the number of correct digits of the approximation roughly quadruples with each iteration.[8] The original presentation, using modern notation, is as follows: To calculate, let be the initial approximation to. Then, successively iterate as:
The values and are exactly the same as those computed by Heron's method. To see this, the second Heron's method step would computeand we can use the definitions of and to rearrange the numerator into:
This can be used to construct a rational approximation to the square root by beginning with an integer. If is an integer chosen so is close to, and is the difference whose absolute value is minimized, then the first iteration can be written as:
The Bakhshali method can be generalized to the computation of an arbitrary root, including fractional roots.[9]
One might think the second half of the Bakhshali method could be used as a simpler form of Heron's iteration and used repeatedly, e.g.however, this isnumerically unstable. Without any reference to the original input value, the accuracy is limited by that of the original computation of, and that rapidly becomes inadequate.
Using the same example as in theHeron's method example, the first iteration gives
Likewise the second iteration givesUnlike in Heron's method, must be computed to 8 digits because the formula for does not correct any error in.
This is a method to find each digit of the square root in a sequence. The technique comes from the work ofFrançois Viète, published c. 1600.[10] This method is based on thebinomial theorem and is essentially an inverse algorithm solving. It is slower than the Babylonian method, but it has several advantages:
Disadvantages are:
Napier's bones include an aid for the execution of this algorithm. The shiftingnth root algorithm is a generalization of this method.
First, consider the case of finding the square root of a numberS, that is the square of a base-10 two-digit numberXY, whereX is the tens digit andY is the units digit. Specifically:S will consist of 3 or 4 decimal digits.
Now to start the digit-by-digit algorithm, we split the digits ofS in two groups of two digits, starting from the right. This means that the first group will be of 1 or 2 digits. Then we determine the value ofX as the largest digit such thatX2 is less than or equal to the first group.We then compute the difference between the first group andX2 and start the second iteration by concatenating the second group to it. This is equivalent to subtracting fromS, and we're left with.We divideS' by 10, then divide it by2X and keep the integer part to try and guessY.We concatenate2X with the tentativeY and multiply it byY. If our guess is correct, this is equivalent to computing: and so the remainder, that is the difference betweenS' and the result, is zero; if the result is higher thanS', we lower our guess by 1 and try again until the remainder is 0.Since this is a simple case where the answer is a perfect square rootXY, the algorithm stops here.
The same idea can be extended to any arbitrary square root computation next. Suppose we are able to find the square root ofS by expressing it as a sum ofn positive numbers such that
By repeatedly applying the basic identity the right-hand-side term can be expanded as
This expression allows us to find the square root by sequentially guessing the values ofs. Suppose that the numbers have already been guessed, then them-th term of the right-hand-side of the above summation is given by where is the approximate square root found so far. Now each new guess should satisfy the recursion where is the sum of all the terms after, i.e. the remainder, such that for all with initialization When the exact square root has been found; if not, then the sum of thes gives a suitable approximation of the square root, with being the approximation error.
For example, in the decimal number system we have where are place holders and the coefficients. At any m-th stage of the square root calculation, the approximate root found so far, and the summation term are given by
Here since the place value of is an even power of 10, we only need to work with the pair of most significant digits of the remainder, whose first term is, at any m-th stage. The section below codifies this procedure.
It is obvious that a similar method can be used to compute the square root in number systems other than the decimal number system. For instance, finding the digit-by-digit square root in the binary number system is quite efficient since the value of is searched from a smaller set of binary digits {0,1}. This makes the computation faster since at each stage the value of is either for or for. The fact that we have only two possible options for also makes the process of deciding the value of atm-th stage of calculation easier. This is because we only need to check if for If this condition is satisfied, then we take; if not then Also, the fact that multiplication by 2 is done by left bit-shifts helps in the computation.
Write the original number in decimal form. The numbers are written similar to thelong division algorithm, and, as in long division, the root will be written on the line above. Now separate the digits into pairs, starting from the decimal point and going both left and right. The decimal point of the root will be above the decimal point of the square. One digit of the root will appear above each pair of digits of the square.
Beginning with the left-most pair of digits, do the following procedure for each pair:
Find the square root of 152.2756.
1 2. 3 4 / \/ 01 52.27 56 01 1*1 <= 1 < 2*2 x=1 01 y = x*x = 1*1 = 1 00 52 22*2 <= 52 < 23*3 x=2 00 44 y = (20+x)*x = 22*2 = 44 08 27 243*3 <= 827 < 244*4 x=3 07 29 y = (240+x)*x = 243*3 = 729 98 56 2464*4 <= 9856 < 2465*5 x=4 98 56 y = (2460+x)*x = 2464*4 = 9856 00 00Algorithm terminates: Answer=12.34
This section uses the formalism fromthe digit-by-digit calculation section above, with the slight variation that we let, with each or.
We iterate all, from down to, and build up an approximate solution, the sum of all for which we have determined the value.
To determine if equals or, we let. If (i.e. the square of our approximate solution including does not exceed the target square) then, otherwise and.
To avoid squaring in each step, we store the difference and incrementally update it by setting with.
Initially, we set for the largest with.
As an extra optimization, we store and, the two terms of in case that is nonzero, in separate variables,:
and can be efficiently updated in each step:
Note that: which is the final result returned in the function below.
ThePython program computes. The algorithm is adigit-by-digit (bit-by-bit) method forinteger square roots.[11]
defisqrt(x:int)->int:assertx>=0,"sqrt input should be non-negative"op:int=x# X_(n+1)res:int=0# c_n# d_n which starts at the highest power of four <= none:int=1whileone<=op:one<<=2# Now 'one' is the largest power of four <= xone>>=2# for dₙ … d₀whileone!=0:ifop>=res+one:# if X_(m+1) ≥ Y_m then a_m = 2^mop-=res+one# X_m = X_(m+1) - Y_mres+=2*one# c_m = c_m + 2*d_mres//=2# c_(m-1) = c_m / 2one//=4# d_(m-1) = d_m / 4# c_(-1)returnres
Faster algorithms, in binary and decimal or any other base, can be realized by using lookup tables—in effect tradingmore storage space for reduced run time.[12]
This sectiondoes notcite anysources. Please helpimprove this section byadding citations to reliable sources. Unsourced material may be challenged andremoved.(May 2020) (Learn how and when to remove this message) |
Pocket calculators typically implement good routines to compute theexponential function and thenatural logarithm, and then compute the square root ofS using the identity found using the properties of logarithms () and exponentials():The denominator in the fraction corresponds to thenth root. In the case above the denominator is 2, hence the equation specifies that the square root is to be found. The same identity is used when computing square roots withlogarithm tables orslide rules.
This method is applicable for finding the square root of and converges best for.This, however, is no real limitation for a computer-based calculation, as in base 2 floating-point and fixed-point representations, it is trivial to multiply by an integer power of 4, and therefore by the corresponding power of 2, by changing the exponent or by shifting, respectively. Therefore, can be moved to the range. Moreover, the following method does not employ general divisions, but only additions, subtractions, multiplications, and divisions by powers of two, which are again trivial to implement. A disadvantage of the method is that numerical errors accumulate, in contrast to single variable iterative methods such as the Babylonian one.
The initialization step of this method iswhile the iterative steps readThen, (while).
The convergence of, and therefore also of, is quadratic.
The proof of the method is rather easy. First, rewrite the iterative definition of asThen it is straightforward to prove by induction thatand therefore the convergence of to the desired result is ensured by the convergence of to 0, which in turn follows from.
This method was developed around 1950 byM. V. Wilkes,D. J. Wheeler andS. Gill[13] for use onEDSAC, one of the first electronic computers.[14] The method was later generalized, allowing the computation of non-square roots.[15]
The following are iterative methods for finding the reciprocal square root ofS which is. Once it has been found, find by simple multiplication:. These iterations involve only multiplication, and not division. They are therefore faster than theBabylonian method. However, they are not stable. If the initial value is not close to the reciprocal square root, the iterations will diverge away from it rather than converge to it. It can therefore be advantageous to perform an iteration of the Babylonian method on a rough estimate before starting to apply these methods.
Goldschmidt's algorithm is an extension ofGoldschmidt division, named after Robert Elliot Goldschmidt,[16][17] which can be used to calculate square roots. Some computers use Goldschmidt's algorithm to simultaneously calculate and.Goldschmidt's algorithm finds faster than Newton-Raphson iteration on a computer with afused multiply–add instruction and either a pipelined floating-point unit or two independent floating-point units.[18]
The first way of writing Goldschmidt's algorithm begins
and iteratesuntil is sufficiently close to 1, or a fixed number of iterations. The iterations converge to andNote that it is possible to omit either and from the computation, and if both are desired then may be used at the end rather than computing it through in each iteration.
A second form, usingfused multiply-add operations, begins
and iteratesuntil is sufficiently close to 0, or a fixed number of iterations. This converges to and
IfN is an approximation to, a better approximation can be found by using theTaylor series of thesquare root function:
As an iterative method, theorder of convergence is equal to the number of terms used. With two terms, it is identical to theBabylonian method. With three terms, each iteration takes almost as many operations as theBakhshali approximation, but converges more slowly.[citation needed] Therefore, this is not a particularly efficient way of calculation. To maximize the rate of convergence, chooseN so that is as small as possible.
Thecontinued fraction representation of a real number can be used instead of its decimal or binary expansion and this representation has the property that the square root of any rational number (which is not already a perfect square) has a periodic, repeating expansion, similar to how rational numbers have repeating expansions in the decimal notation system.
Quadratic irrationals (numbers of the form, wherea,b andc are integers), and in particular, square roots of integers, haveperiodic continued fractions. Sometimes what is desired is finding not the numerical value of a square root, but rather itscontinued fraction expansion, and hence its rational approximation. LetS be the positive number for which we are required to find the square root. Then assuminga to be a number that serves as an initial guess andr to be the remainder term, we can write Since we have, we can express the square root ofS as
By applying this expression for to the denominator term of the fraction, we have:
Compact notation—The numerator/denominator expansion for continued fractions (above) is cumbersome to write as well as to embed in text formatting systems. So mathematicians have devised several alternative notations(see:Generalized continued fraction § Notation) such as:
When throughout, an even more compact notation is:[Note 7]For repeating continued fractions (which all square roots of non-perfect squares do), the repetend is represented only once, with an overline to signify a non-terminating repetition of the overlined part:[Note 8]
For√2, the value ofa = 1, so its representation is:
Proceeding this way, we get ageneralized continued fraction for the square root as
The first step to evaluating such a fraction[19] to obtain a root is to do numerical substitutions for the root of the number desired, and number of denominators selected. For example, in canonical form,r = 1 and for√2,a = 1, so the numerical continued fraction for 3 denominators is:
Step 2 is to reduce the continued fraction from the bottom up, one denominator at a time, to yield a rational fraction whose numerator and denominator are integers. The reduction proceeds thus (taking the first three denominators):
Finally (step 3), divide the numerator by the denominator of the rational fraction to obtain the approximate value of the root: rounded to three digits of precision.
The actual value of√2 is 1.41 to three significant digits. The relative error is 0.17%, so the rational fraction is good to almost three digits of precision. Taking more denominators gives successively better approximations: four denominators yields the fraction, good to almost 4 digits of precision, etc.
The following are examples of square roots, their simple continued fractions, and their first terms — calledconvergents — up to and including denominator 99:
| √S | ~decimal | continued fraction | convergents |
|---|---|---|---|
| √2 | 1.41421 | ||
| √3 | 1.73205 | ||
| √5 | 2.23607 | ||
| √6 | 2.44949 | ||
| √10 | 3.16228 | ||
| 1.77245 | |||
| 1.64872 | |||
| 1.27202 |
In general, the larger the denominator of a rational fraction, the better the approximation. It can also be shown that truncating a continued fraction yields a rational fraction that is the best approximation to the root of any fraction with denominator less than or equal to the denominator of that fraction — e.g., no fraction with a denominator less than or equal to 70 is as good an approximation to√2 as 99/70.
A number is represented in afloating point format as which is also calledscientific notation. Its square root is and similar formulae would apply for cube roots and logarithms. On the face of it, this is no improvement in simplicity, but suppose that only an approximation is required: then just is good to an order of magnitude. Next, recognise that some powers,p, will be odd, thus for 3141.59 = 3.14159×103 rather than deal with fractional powers of the base, multiply the mantissa by the base and subtract one from the power to make it even. The adjusted representation will become the equivalent of 31.4159×102 so that the square root will be√31.4159×101.
If the integer part of the adjusted mantissa is taken, there can only be the values 1 to 99, and that could be used as an index into a table of 99 pre-computed square roots to complete the estimate. A computer using base sixteen would require a larger table, but one using base two would require only three entries: the possible bits of the integer part of the adjusted mantissa are 01 (the power being even so there was no shift, remembering that anormalised floating point number always has a non-zero high-order digit) or if the power was odd, 10 or 11, these being the firsttwo bits of the original mantissa. Thus, 6.25 = 110.01 in binary, normalised to 1.1001 × 22 an even power so the paired bits of the mantissa are 01, while .625 = 0.101 in binary normalises to 1.01 × 2−1 an odd power so the adjustment is to 10.1 × 2−2 and the paired bits are 10. Notice that the low order bit of the power is echoed in the high order bit of the pairwise mantissa. An even power has its low-order bit zero and the adjusted mantissa will start with 0, whereas for an odd power that bit is one and the adjusted mantissa will start with 1. Thus, when the power is halved, it is as if its low order bit is shifted out to become the first bit of the pairwise mantissa.
A table with only three entries could be enlarged by incorporating additional bits of the mantissa. However, with computers, rather than calculate an interpolation into a table, it is often better to find some simpler calculation giving equivalent results. Everything now depends on the exact details of the format of the representation, plus what operations are available to access and manipulate the parts of the number. For example,Fortran offers anEXPONENT(x) function to obtain the power. Effort expended in devising a good initial approximation is to be recouped by thereby avoiding the additional iterations of the refinement process that would have been needed for a poor approximation. Since these are few (one iteration requires a divide, an add, and a halving) the constraint is severe.
Many computers follow theIEEE (or sufficiently similar) representation, and a very rapid approximation to the square root can be obtained for starting Newton's method. The technique that follows is based on the fact that the floating point format (in base two) approximates the base-2 logarithm. That is
So for a 32-bit single precision floating point number in IEEE format (where notably, the power has abias of 127 added for the represented form) you can get the approximate logarithm by interpreting its binary representation as a 32-bit integer, scaling it by, and removing a bias of 127, i.e.
For example, 1.0 is represented by ahexadecimal number0x3F800000, which would represent if taken as an integer. Using the formula above you get, as expected from. In a similar fashion you get 0.5 from 1.5 (0x3FC00000).
To get the square root, divide the logarithm by 2 and convert the value back. The following program demonstrates the idea. The exponent's lowest bit is intentionally allowed to propagate into the mantissa. One way to justify the steps in this program is to assumeb is the exponent bias andn is the number of explicitly stored bits in the mantissa and then show that
/* Assumes that float is in the IEEE 754 single precision floating point format */#include<stdint.h>unionFloatUInt{floatf;uint32_ti;}floatsqrtApprox(floatz){unionFloatUIntval={z};// Convert type, preserving bit pattern/* * To justify the following code, prove that * * ((((val.i / 2^m) - b) / 2) + b) * 2^m = ((val.i - 2^m) / 2) + ((b + 1) / 2) * 2^m) * * where * * b = exponent bias * m = number of mantissa bits */val.i-=1<<23;// Subtract 2^m.val.i>>=1;// Divide by 2.val.i+=1<<29;// Add ((b + 1) / 2) * 2^m.// Interpret again as floatreturnval.f;}
The three mathematical operations forming the core of the above function can be expressed in a single line. An additional adjustment can be added to reduce the maximum relative error. So, the three operations, not including the cast, can be rewritten as
val.i=(1<<29)+(val.i>>1)-(1<<22)+a;
wherea is a bias for adjusting the approximation errors. For example, witha = 0 the results are accurate for even powers of 2 (e.g. 1.0), but for other numbers the results will be slightly too big (e.g. 1.5 for 2.0 instead of 1.414... with 6% error). Witha = −0x4B0D2, the maximum relative error is minimized to ±3.5%.
If the approximation is to be used for an initial guess forNewton's method to the equation, then the reciprocal form shown in the following section is preferred.
A variant of the above routine is included below, which can be used to compute thereciprocal of the square root, i.e., instead, was written by Greg Walsh. The integer-shift approximation produced a relative error of less than 4%, and the error dropped further to 0.15% with one iteration ofNewton's method on the following line.[20] In computer graphics it is a very efficient way to normalize a vector.
unionFloatInt{floatx;inti;};floatinv_sqrt(floatx){floatxhalf=0.5f*x;unionFloatIntu;u.x=x;u.i=0x5f375a86-(u.i>>1);// The next line can be repeated any number of times to increase accuracyu.x=u.x*(1.5f-xhalf*u.x*u.x);returnu.x;}
Some VLSI hardware implements inverse square root using a second degree polynomial estimation followed by aGoldschmidt iteration.[21]
IfS < 0, then its principal square root is
IfS = a+bi wherea andb are real andb ≠ 0, then its principal square root is
This can be verified by squaring the root.[22][23]Here
is themodulus ofS. The principal square root of acomplex number is defined to be the root with the non-negative real part.
decimal.MAX_PREC