How does Math.sqrt work in javascript?

Asked

Viewed 2,440 times

13

All right, I know it returns the square root of a number. But, what numerical operations it does to bring this result?

  • 2

    I don’t know exactly how Javascript does it, but there are many ways. One of the most "famous" is the Babylonian Method where the root value (initially kicked from the number of digits of the value to which one wants to extract the root) is "adjusted" by the mean of super and over-estimated values until it converges (that is, no longer changes - see the example on the Wikipedia page referenced).

2 answers

10


Like me had already commented, i don’t know exactly how Javascript does it. Second the answer from Mr @Sergio, browsers are free to implement natively as they see fit (and probably also use the native implementations of the languages that were used to create them).

In any case, one of the simplest implementations stems from Newton’s method (although it was discovered at least 16 centuries earlier - more details on Wikipedia). It’s called the Babylonian Method (Babylonian Method).

The idea is simple. Calculate raíz quadrada de S is the same as solving the equation: equação similar, since the value of x found will be equal to the sought square root.

Roughly speaking, the resolution by newton’s method is to iteratively improve the root value* of the estimated function by subtracting from it a still existing "error rate".

*That is, the value of x that makes the function result in 0 - not to be confused with the value of the square "root".

The error rate is given by the ratio of the value returned by the function to the value returned by the first derivative of the function:

taxa de erro

Thus, by subtracting this error rate from a chosen initial value x0, a new value is obtained x1 closer to the desired actual value:

novo valor

This operation can be repeated (subtracting the error from the new value) until a value sufficiently close to the real (convergence) is obtained. The animation below, reproduced from the Wikipedia link about the method, illustrates this iterative process.

inserir a descrição da imagem aqui

The red line, tangent in the curve at the intersection of the value of x chosen at the time, is the derivative of the function at that point. It cuts the axis x at another point, obtained by subtraction. Thus, one observes how gradually the new values converge to the point of interest (the root of the function, that is, the value of x where the curve cuts the axis x since it is desired to equal the function to 0).

How the function of interest is equação similar (where the root of the function will be equal to the square root of S), it can be worked algebraically as described in Wikipedia (in the first referenced link, on estimation methods):

inserir a descrição da imagem aqui

That is, just iteratively process the value...

inserir a descrição da imagem aqui

... until convergence, that is, until the next estimate changes from the previous one (based on a desired precision).

It is possible to implement this method in Javascript with the following code (note the deliberate choice of precision with 5 decimal places in the call .toFixed(5)):

function bab_sqrt(fValue) {
    if(fValue < 0)
        return 0;

    var fNext = fValue.toString().length * 100; // "Chuta" o valor inicial da raíz com base no número de dígitos
    var fPrev = 0;

    // Processa enquanto não convergir
    // (isto é, enquanto fNext for diferente de fPrev com precisão de 5 decimais)
    do {
        fPrev = fNext;
        fNext = 0.5 * (fPrev + fValue / fPrev);
    } while(fNext.toFixed(5) != fPrev.toFixed(5))

    return fNext;
}

But note that it does not work (always returns 0) for negative/complex numbers (such as the native implementation, which returns NaN).

Here’s a more complete example, comparing native results (implemented with Math.sqrt browser) and manual (implemented with the above function).

function doCalc() {
    var fValue = parseFloat(document.getElementById("value").value);
    
    var fRootNative = Math.sqrt(fValue);
    var fRootCalc = bab_sqrt(fValue);
    
    document.getElementById("result").innerHTML = "<p>Raíz (nativa) = " + fRootNative.toFixed(5) + "</p><p>Raíz (calculada) = " + fRootCalc.toFixed(5) + "</p>";
}

function bab_sqrt(fValue) {
    if(fValue < 0)
        return 0;

    var fNext = fValue.toString().length * 100; // "Chuta" o valor inicial da raíz com base no número de dígitos
    var fPrev = 0;

    // Processa enquanto não convergir
    // (isto é, enquanto fNext for diferente de fPrev com precisão de 5 decimais)
    do {
        fPrev = fNext;
        fNext = 0.5 * (fPrev + fValue / fPrev);
    } while(fNext.toFixed(5) != fPrev.toFixed(5))
    
    return fNext;
}
Valor para extração da raíz: <input type="text" id="value"><br>
<button onclick="doCalc()">Calcular</button>

<p id="result"></p>

  • 1

    Very good reply @Luiz Vieira, I liked the reference to the Newton method , although I found the question a little obvious for Sergio’s appointment, congratulations.

  • 2

    Thank you, @Wellingtonsilvaribeiro. I only posted the answer because it could help the AP if it was an academic work. In fact, Sergio’s answer (along with the bfavaretto comment) is the one that really answers the question, in the sense that the implementation is in charge of the browser. This information, although it may seem trivial, can be important depending on the use of Javascript that someone will do (scientific or in games, for example).

  • 1

    @Luiz Vieira, perfect answer. Although I was not perfectly clear, I admit, in my question you captured the essence, man. I wanted to know yes how the JS calculated, and in that the reply of friend Sergio helped a lot, but his answered the question that came to my head. I knew it was by pet but had no idea of the calculation. Thank you very much!

  • 1

    For nothing. Still, it is worth remembering that there are many other methods. The comment from @bfavaretto, for example, it presents a code that (after a very superficial check) seems to use the digit-to-digit calculation method. You have a description of him, too there on the Wikipedia link that I’ve already mentioned. Probably this is the implementation used by browsers. :)

  • P.S.: Newton’s method is the next suggestion in the IEEE 754 algorithms in the section "Other Methods", item a.

8

To Ecmascript (ES6) says:

Math.sqrt ( x )

Returns an implementation-dependent approximation to the square root of x.
If x is Nan, the result is Nan.
If x is Less than 0, the result is Nan.
If x is +0, the result is +0.
If x is 0, the result is 0.
If x is + , the result is +.

Translating the important part would be:

Returns a square root approximation of x dependent/depending on implementation.

In other words, each browser can implement differently. That doesn’t help your question much... but at least you know it’s not a normalized value or with an equal rule for all browsers (at least there’s no such obligation).

  • 2

    Ecmascript 5 says the same thing. And recommends using the algorithms of IEEE 754, which in turn recommends using hardware (processor) implementation when available.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.