Alright, I know that it returns the square root of a number. But what numerical operations does it do to bring this result?
Alright, I know that it returns the square root of a number. But what numerical operations does it do to bring this result?
As I had commented , I I do not know exactly how Javascript does. According to the reply from colleague @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 comes from Newton's method (although it was discovered at least 16 centuries earlier - more details on Wikipedia ). It is called the Babylonian Method .
The idea is simple. Calculating isthesameassolvingtheequation:, since the value of found will be equal to the searched square root.
In general terms, Newton's method of Newton's resolution is to iterately improve the value of the root * of the function estimated by subtracting from it an "error rate" that still exists.
That is, the value ofx
that causes the function to result in 0
- not to be confused with the value of the "root" square.
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:
Thus, by subtracting this error rate from an initial value chosen ,yougetanewvalue closer to the desired real value:
This operation can be repeated (subtracting the error of the new value) until a value close enough to the real one (convergence) is obtained. The animation below, reproduced from the Wikipedia link on the method, illustrates this iterative process.
Theredline,tangenttothecurveatthepointofintersectionofthex
valuecurrentlychosen,isthederivativeofthefunctionatthatpoint.Itcutsthex
axistoanotherpoint,obtainedbysubtraction.Thus,itisobservedhowgraduallythenewvaluesconvergetothepointofinterest(therootofthefunction,thatis,thevalueofx
wherethecurvecutsthex
axissincewewanttoequatethefunctiona0
).
Sincethefunctionofinterestis (where the root of the function will be equal to the square root of S
), it can be algebraically worked as described in Wikipedia (in the first link referenced, about estimation methods):
Thatis,yousimplyprocessthevalueiteratively...
... until convergence, that is, until the next estimate does not change from the previous one (based on a desired precision).
You can implement this method in Javascript with the following code (note the deliberate choice of precision with 5 decimal places in the .toFixed(5)
call):
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 (just like the native implementation, which returns NaN
).
Here is a more complete example, which compares the native results (implemented with% 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>
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 an approximation of the square root of x dependent / consonant of the implementation.
That is, each Browser can implement differently. This does not really help your question ... but at least you know it's not a normalized value or an equal rule for all browsers (at least there's no such obligation).