Comments (3)
There is an old proposal for seeded PRNG from 2018, and a very new proposal for common utility functions. Missing from the proposals are specialized random distributions. For these an API like this (modeled after part of C++'s <random>
library) would be easy to use, easy to implement, and integrate well with the seeded PRNG proposal and other user-provided RNGs.
// distribution
export type Distribution = (randomSource: () => number) => number;
// exponential-distribution
export interface ExponentialDistributionParams {
rate?: number;
}
export function exponentialDistribution(
params?: ExponentialDistributionParams,
): Distribution;
// normal-distribution
export interface NormalDistributionParams {
mean?: number;
stddev?: number;
}
export function normalDistribution(
params?: NormalDistributionParams,
): Distribution;
// …
Example usage
Say a user wants to simulate random events that on average occur every second.
import { delay } from "jsr:@std/async/delay";
import { SECOND } from "jsr:@std/datetime/constants";
import { exponentialDistribution } from "jsr:@std/random/exponential-distribution";
const dist = exponentialDistribution({ rate: 1 / SECOND });
for (;;) {
await delay(dist(Math.random));
console.log("event!");
}
What the implementation may look like
// exponential_distribution.ts
const { log } = Math;
export function exponentialDistribution(
params?: ExponentialDistributionParams,
): Distribution {
const invRate = -1 / (params?.rate ?? 1);
return (s) => invRate * log(1 - s());
}
from deno_std.
@0f-0b
Wow, seems these proposals didn't get much traction 😅
But it's nice seeing that they've been updated recently.
I think it's a safe choice to provide them until they're eventually are built-ins then, as they're only in stage 0/1.
The second proposal contains some really useful functions too that I think it'd be nice to polyfill in the meantime, mainly shuffle( array )
and pickFromList( array )
. I think a pickFromObject( Record<string, number> )
could be nice to provide a weighted pick from a given record.
Anyway I think the API you provided are is pretty straightforward so I'm ok with it.
I like the fact that it make combination of different distributions easy and it's also compatible with the current Math.random
out of the box.
So for the base PRNG, would it be a good idea to stay close to what is suggested in the first proposal ?
export function seededPRNG(
{seed:number}
): {
random:() => number
randomSeed:() => number
readonly seed: number
}
from deno_std.
A utility for converting arbitrary strings into suitable prng seeds would also be useful.
shuffle
would be useful to include as it's easy to implement wrong or with suboptimal efficiency. pickFromList
, randBetween
, randInt
etc (subject to bikeshedding about names) are maybe too simple to be strictly necessary but might still be worthwhile...? I'm not sure exactly how pickFromObject
would work, but picking with weights can definitely be useful:
function pickWeighted<T extends { weight: number }>(items: readonly T[], random = Math.random): T {
const max = Object.values(items).reduce((sum, { weight }) => sum + weight, 0)
const rand = random() * max
let total = 0
for (const item of items) {
total += item.weight
if (rand < total) {
return item
}
}
return items[0]
}
from deno_std.
Related Issues (20)
- propsal: move some modules out of `@std/fmt` HOT 5
- test(fs): do not write files in source tree during test
- test(http): http test cases should pass when it's executed from `./http` directory
- suggestion: remove `getAvailablePort()` from `@std/net` HOT 2
- Check the usage of TextDecoder
- Rename the repository to `std` HOT 1
- question(collections): `intersect()` function name differ from Set method name HOT 1
- docs: more thoroughly document `expect.toThrow()` behavior HOT 2
- feat request: add a pluralize word function HOT 4
- feat request: expose publicly `capitalizeWord` (or similar) HOT 9
- http/file-server, media_types: new addition `application/mp4` to mime db overrides `video/mp4` and breaks some net players HOT 6
- isGlob and globToRegExp do not support windows paths HOT 1
- feat req: add enums for WebSocket status HOT 1
- feat req (html): add a validator for custom name elements ? HOT 4
- to-do: add doc check for JSDoc tags that aren't needed
- to-do(yaml): document different YAML schemas
- proposal: remove `examplePath` option from `@std/dotenv/load`
- proposal: remove `defaultPath` from `@std/dotenv/load`
- Performance: `levenshteinDistance` becomes extremely slow for large edit distances HOT 1
- The windows logic in std/path breaks in DNT
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from deno_std.