Created
February 14, 2017 03:35
-
-
Save jeasonstudio/c4c6b36a892eae5644f655e909de660b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const _JINGDU = 1e-6 | |
function judgeZero(tag) { | |
return Math.abs(tag) <= _JINGDU | |
} | |
// 暴力开平方 | |
function baoliSqrt(num) { | |
console.time("Baoli SQRT") | |
var i | |
for (i = 0; Math.abs(num - i * i) > _JINGDU; i += _JINGDU); | |
console.log(i) | |
console.timeEnd("Baoli SQRT") | |
} | |
// 原生库函数开平方 | |
function localSqrt(num) { | |
console.time('Local SQRT') | |
var i = Math.sqrt(num) | |
console.log('Local SQRT:', i) | |
console.timeEnd('Local SQRT') | |
} | |
// 牛顿开平方 | |
function newtonSqrt(num) { | |
console.time("Newton SQRT") | |
var _avg = num | |
var last_avg = 0 | |
while (Math.abs(_avg - last_avg) > _JINGDU) { | |
last_avg = _avg | |
_avg = (_avg + num / _avg) / 2 | |
} | |
console.log("Newton SQRT:", _avg) | |
console.timeEnd("Newton SQRT") | |
} | |
// 暴力加牛顿开方 | |
function baoliAndNewtonSqrt(num) { | |
console.time('BaoliAndNewton SQRT') | |
var _avg, i = 0, | |
last_avg = 0 | |
for (i = 0; i * i < num; i += 0.1); | |
_avg = i; | |
while (Math.abs(_avg - last_avg) > _JINGDU) { | |
last_avg = _avg; | |
_avg = (_avg + num / _avg) / 2; | |
} | |
console.log('BaoliAndNewton SQRT:', _avg) | |
console.timeEnd('BaoliAndNewton SQRT') | |
} | |
// 二分法开方 | |
function erfenSqrt(num) { | |
console.time('Erfen SQRT') | |
var _low = 0, | |
_high = num, | |
_mid = 9999999, | |
last_mid = 0 | |
while (Math.abs(_mid - last_mid) > _JINGDU) { | |
last_mid = _mid; | |
_mid = (_low + _high) / 2; | |
if (_mid * _mid > num) | |
_high = _mid; | |
if (_mid * _mid < num) | |
_low = _mid; | |
} | |
console.log('Erfen SQRT:', _mid) | |
console.timeEnd('Erfen SQRT') | |
} | |
// function invSqrt(num) { | |
// float xhalf = 0.5f* num | |
// int i = *(int *)& num // get bits for floating VALUE | |
// i = 0x5f375a86 - (i >> 1); // gives initial guess y0 | |
// x = *(float *)& i; // convert bits BACK to float | |
// x = x * (1.5f- xhalf * x * x); // Newton step, repeating increases accuracy | |
// return x; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment