Last active
February 5, 2019 12:46
-
-
Save LoeizD/893fc45008cf909069bbda1aadf39cf0 to your computer and use it in GitHub Desktop.
Algo to get the n-th root of a number using a false montecarlo method. Fasle because the random number generator is weak but sufficient.
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
// By Corentin Derbré | |
function pow(num, exp) { | |
let ret = num | |
for (let j = 1; j < exp; j++) { | |
ret *= num | |
} | |
return ret | |
} | |
function isEven(num) { | |
return !( num & 1 ) | |
} | |
function random(seed1, seed2) { | |
let rand | |
if (isEven(seed1) && isEven(seed2)) { | |
rand = 0.01 | |
} | |
else if (isEven(seed1) && !isEven(seed2)) { | |
rand = 0.33 | |
} | |
else if (!isEven(seed1) && isEven(seed2)) { | |
rand = 0.66 | |
} | |
else if (!isEven(seed1) && !isEven(seed2)) { | |
rand = 0.99 | |
} | |
return rand | |
} | |
function nrt(num, root) { | |
if (num < 0 && isEven(root)) { | |
return undefined | |
} | |
let sign = 1 | |
if (num < 0) { | |
num *= -1 | |
sign *= -1 | |
} | |
const tries = 1000 | |
let upperBound = num + 1 | |
let lowerBound = 0 | |
let guess = random(upperBound, upperBound * 0.23) * upperBound + lowerBound | |
for (let i = 0; i < tries; i++) { | |
if ( pow(guess, root) < num ) { | |
lowerBound = guess | |
} | |
else { | |
upperBound = guess | |
} | |
guess = random(upperBound, guess) * ( upperBound - lowerBound ) + lowerBound | |
} | |
return guess * sign | |
} | |
console.log(nrt(-1243, 6)) // unfedined | |
console.log(nrt(81234, 7)) // 5.0279519632 | |
console.log(nrt(-2438, 7)) // -3.0469263549 | |
console.log(nrt(81, 2)) // 9 | |
console.log(nrt(85729437539874902, 4)) // 17111.279829679 | |
console.log(nrt(0, 1)) // 0 | |
console.log(nrt(0, 2)) // 0 | |
console.log(nrt(0, 3)) // 0 | |
console.log(nrt(1, 1)) // 1 | |
console.log(nrt(1, 2)) // 1 | |
console.log(nrt(1, 5)) // 1 | |
console.log(nrt(314, 1)) // 314 | |
console.log(nrt(165.32, 3)) // 5.488349996236 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment