Difference between revisions of "API:RNG::next"
From Spherical
Bruce Pascoe (talk | contribs) (New page: RNG::next()) |
Bruce Pascoe (talk | contribs) (Reorganize page, add sub-headings for organization, add description) |
||
Line 1: | Line 1: | ||
{{DISPLAYTITLE:RNG::next()}} | {{DISPLAYTITLE:RNG::next()}} | ||
− | <tt>'''RNG::next()'''</tt> | + | The <tt>'''RNG::next()'''</tt> method returns a random floating-point number in the range <tt>[0,1)</tt>. |
− | + | === Usage === | |
''number'' = ''rng_object''.'''next'''(); | ''number'' = ''rng_object''.'''next'''(); | ||
__TOC__ | __TOC__ | ||
− | == | + | == API Information == |
− | / | + | === Description === |
− | + | ||
− | + | <tt>'''RNG::next()'''</tt> generates a pseudorandom floating-point value greater than or equal to 0 but less than 1 and returns the value so generated. The value this function returns is entirely determined by the current state of the <tt>RNG</tt> instance before the call (see <tt>[[API:RNG::state|RNG::state]]</tt>). After calling this function, the state is advanced so a different value will be generated next time. If you save the state before <tt>RNG.next()</tt>, then restore it afterwards and call <tt>RNG.next()</tt> again, the same value will be generated. | |
− | + | ||
− | let | + | === Examples === |
+ | |||
+ | ==== Shuffle items in an array ==== | ||
+ | |||
+ | let items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] | ||
let rnGen = new RNG(); | let rnGen = new RNG(); | ||
− | for (let i = | + | for (let i = items.length - 1; i > 0; --i) { |
− | let j = Math.floor(rnGen.next() * (i + 1)); // | + | let j = Math.floor(rnGen.next() * (i + 1)); // discrete [0,i] |
− | let orig_i = | + | let orig_i = items[i]; |
− | + | items[i] = items[j]; | |
− | + | items[j] = orig_i; | |
} | } | ||
[[Category:Sphere 2 API]] | [[Category:Sphere 2 API]] |
Revision as of 15:45, 9 August 2017
The RNG::next() method returns a random floating-point number in the range [0,1).
Usage
number = rng_object.next();
API Information
Description
RNG::next() generates a pseudorandom floating-point value greater than or equal to 0 but less than 1 and returns the value so generated. The value this function returns is entirely determined by the current state of the RNG instance before the call (see RNG::state). After calling this function, the state is advanced so a different value will be generated next time. If you save the state before RNG.next(), then restore it afterwards and call RNG.next() again, the same value will be generated.
Examples
Shuffle items in an array
let items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] let rnGen = new RNG(); for (let i = items.length - 1; i > 0; --i) { let j = Math.floor(rnGen.next() * (i + 1)); // discrete [0,i] let orig_i = items[i]; items[i] = items[j]; items[j] = orig_i; }