Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Web] Implement linear congruential generator, make runtime seedable #16722

Merged
merged 3 commits into from
Mar 15, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fix lint
CharlieFRuan committed Mar 14, 2024
commit 39ff09094608a161b6dde7c4fa998216bea9922c
12 changes: 6 additions & 6 deletions web/src/support.ts
Original file line number Diff line number Diff line change
@@ -77,10 +77,10 @@ export function wasmPath(): string {

/**
* Linear congruential generator for random number generating that can be seeded.
*
*
* Follows the implementation of `include/tvm/support/random_engine.h`, which follows the
* sepcification in https://en.cppreference.com/w/cpp/numeric/random/linear_congruential_engine.
*
*
* Note `Number.MAX_SAFE_INTEGER = 2^53 - 1`, and our intermediates are strictly less than 2^48.
*/

@@ -104,7 +104,7 @@ export class LinearCongruentialGenerator {
/**
* Sets `rand_state` after normalized with `modulus` to ensure that it is within range.
* @param seed Any integer. Used to set `rand_state` after normalized with `modulus`.
*
*
* Postcondition: pass `checkRandState()`, i.e. rand_state > 0 and is an integer.
*/
setSeed(seed: number) {
@@ -120,12 +120,12 @@ export class LinearCongruentialGenerator {

/**
* Generate the next integer in the range (0, this.modulus) non-inclusive, updating `rand_state`.
*
*
* Postcondition: pass `checkRandState()`, i.e. rand_state > 0 and is an integer.
*/
nextInt(): number {
// `intermediate` is always < 2^48, hence less than `Number.MAX_SAFE_INTEGER` due to the
// invariants as commented in the constructor.
// invariants as commented in the constructor.
const intermediate = this.multiplier * this.rand_state + this.increment;
this.rand_state = intermediate % this.modulus;
this.checkRandState();
@@ -134,7 +134,7 @@ export class LinearCongruentialGenerator {

/**
* Generates random float between (0, 1) non-inclusive, updating `rand_state`.
*
*
* Postcondition: pass `checkRandState()`, i.e. rand_state > 0 and is an integer.
*/
randomFloat(): number {