-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqrt.js
64 lines (57 loc) · 1.21 KB
/
sqrt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 2018-10-22
* @copyright 2018 LinWei
* @author LinWei
*
* @description
* Calculate the square root of a number.
* See (`Math.sqrt`)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt]
*
* @param {number} x A non-negative number.
* @return {number} Return the square root.
* @example
*
* Math._sqrt(16)
* // => 4
*
* Math._sqrt('0x10')
* // => 4
*
* Math._sqrt(-1)
* // => NaN
*
* Math._sqrt(Infinity)
* // => Infinity
*/
if (!Math._sqrt) {
Math._sqrt = (function() {
"use strict";
var abs = function(value) {
return value >= 0 ? value : -value;
};
var square = function(value) {
return value * value;
};
var diff = function(sqrt, x) {
return square(sqrt) - x;
};
var sqrt = function(x) {
var sqrt = x,
i = 0;
while (abs(diff(sqrt, x))) {
sqrt = (sqrt + x / sqrt) / 2;
if (i++ > 2e+6) {
break;
}
}
return sqrt;
};
return function(x) {
if (x === undefined || x < 0) {
return NaN;
}
x = +x;
return sqrt(x);
};
})();
}