Created
January 22, 2011 22:08
-
-
Save ynkdir/791546 to your computer and use it in GitHub Desktop.
v8 Math.random()
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
" v8 r6432: v8.cc | |
" Random number generator using George Marsaglia's MWC algorithm. | |
function! Srand(seed) | |
return s:rand(a:seed) | |
endfunction | |
function! Rand() | |
return s:rand() | |
endfunction | |
function! Random() | |
return s:random() | |
endfunction | |
let s:hi = 0 | |
let s:lo = 0 | |
function! s:srand(seed) | |
if a:seed < 0 | |
let s:hi = (a:seed - 0x80000000) / 0x10000 + 0x8000 | |
let s:lo = (a:seed - 0x80000000) % 0x10000 | |
else | |
let s:hi = a:seed / 0x10000 + 0x8000 | |
let s:lo = a:seed % 0x10000 | |
endif | |
endfunction | |
function! s:rand() | |
if s:hi == 0 | |
let s:hi = s:random_seed() | |
endif | |
if s:lo == 0 | |
let s:lo = s:random_seed() | |
endif | |
if s:hi < 0 | |
let hi = s:hi - 0x80000000 | |
let hi = 36969 * (hi % 0x10000) + (hi / 0x10000 + 0x8000) | |
else | |
let hi = s:hi | |
let hi = 36969 * (hi % 0x10000) + (hi / 0x10000) | |
endif | |
if s:lo < 0 | |
let lo = s:lo - 0x80000000 | |
let lo = 18273 * (lo % 0x10000) + (lo / 0x10000 + 0x8000) | |
else | |
let lo = s:lo | |
let lo = 18273 * (lo % 0x10000) + (lo / 0x10000) | |
endif | |
let s:hi = hi | |
let s:lo = lo | |
return (hi * 0x10000) + ((lo < 0 ? lo - 0x80000000 : lo) % 0x10000) | |
endfunction | |
function! s:random() | |
let n = s:rand() | |
if n < 0 | |
return (n - 0x80000000) / 4294967295.0 + (0x40000000 / (4294967295.0 / 2.0)) | |
else | |
return n / 4294967295.0 | |
endif | |
endfunction | |
" V8 uses C runtime random function for seed and initialize it with time. | |
let s:seed = float2nr(fmod(str2float(reltimestr(reltime())) * 256, 2147483648.0)) | |
function! s:random_seed() | |
let s:seed = s:seed * 214013 + 2531011 | |
return (s:seed < 0 ? s:seed - 0x80000000 : s:seed) / 0x10000 % 0x8000 | |
endfunction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment