Coder Social home page Coder Social logo

Comments (3)

0f-0b avatar 0f-0b commented on July 18, 2024 1

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.

lowlighter avatar lowlighter commented on July 18, 2024 1

@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.

lionel-rowe avatar lionel-rowe commented on July 18, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.