Skip to content

Commit

Permalink
feat(random): add IRandom.probability()
Browse files Browse the repository at this point in the history
- add impl for ARandom base class
  • Loading branch information
postspectacular committed Aug 12, 2023
1 parent 58fc51c commit efdd49c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
9 changes: 8 additions & 1 deletion packages/random/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface INorm {
norm(scale?: number): number;
/**
* Similar to {@link INorm.norm}, but returns values in either the
* `[min..max)` or in the `(-max...min]` interval (i.e. excluding values in
* `[min..max)` or in the `(-max...-min]` interval (i.e. excluding values in
* the `(-min..min)` range). Both `min` and `max` MUST be >= 0.
*
* @remarks
Expand Down Expand Up @@ -44,6 +44,13 @@ export interface IRandom extends INorm {
* @param max - default 1
*/
float(max?: number): number;
/**
* Calls {@link IRandom.float} and returns true iff result is < `p`
* (assumed to be in [0..1] interval).
*
* @param p
*/
probability(p: number): boolean;
/**
* Returns float in [min..max) interval.
*
Expand Down
4 changes: 4 additions & 0 deletions packages/random/src/arandom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export abstract class ARandom implements IRandom {
return this.int() * INV_MAX * norm;
}

probability(p: number) {
return this.float() < p;
}

norm(norm = 1) {
return (this.int() * INV_MAX - 0.5) * 2 * norm;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/random/src/coin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { SYSTEM } from "./system.js";
* quality of given {@link IRandom}) PRNG.
*
* @remarks
* Also see {@link fairCoin}.
* Also see {@link fairCoin} and {@link IRandom.probability}.
*
* @param rnd -
*/
Expand Down

0 comments on commit efdd49c

Please sign in to comment.