pure-rand
pure-rand copied to clipboard
Document float/double algorithms
How to generate floats or doubles out of an integer value?
Note: We have snippets doing so in fast-check
Yes, please add. Baffling to have a prng library with no way of generating floats.
How to generate floats or doubles out of an integer value?
Note: We have snippets doing so in fast-check
Hi! Where can I find the snippets?
From https://fast-check.dev/docs/core-blocks/arbitraries/primitives/number/#float:
fc.noBias(fc.integer({ min: 0, max: (1 << 24) - 1 }).map((v) => v / (1 << 24)));
// generate a in range [0 (included), (1 << 24) - 1 (included)] then compute "a / (1 << 24)"
From https://fast-check.dev/docs/core-blocks/arbitraries/primitives/number/#double:
fc.noBias(
fc
.tuple(fc.integer({ min: 0, max: (1 << 26) - 1 }), fc.integer({ min: 0, max: (1 << 27) - 1 }))
.map((v) => (v[0] * Math.pow(2, 27) + v[1]) * Math.pow(2, -53)),
);
// generate a in range [0 (included), (1 << 26) - 1 (included)]
// generate b in range [0 (included), (1 << 27) - 1 (included)]
// then compute "(a * Math.pow(2, 27) + b) * Math.pow(2, -53)"
fc.noBias(fc.integer({ min: 0, max: (1 << 24) - 1 }).map((v) => v / (1 << 24)));
Thanks!
I'm just doing import fc from 'fast-check' fc.noBias(fc.integer({ min: 0, max: (1 << 24) - 1 }).map((v) => v / (1 << 24)));
But get fc.noBias is not a function
I installed with pnpm and can see the Arbitrary
class within fc
No need to use fast-check if the only thing you need is to generate random floating point value. My example with fast-check was just a quick extract of a code doing the conversion of an integer value to a floating point one.
Regarding noBias
, the fc.noBias
has not been rolled-out yet. For now it should be fc.integer({ min: 0, max: (1 << 24) - 1 }).noBias().map((v) => v / (1 << 24))
.
map((v) => v / (1 << 24)));
Thanks for the clarification.
I had tried that int method and it worked. I also did,
import fc from 'fast-check'
const min = 1.5;
const max = 5.7;
const min32 = Math.fround(min);
const max32 = Math.fround(max);
// Generate a random float within the specified range
const randomFloatArbitrary = fc.float({ min: min32, max: max32 }).noBias()
const randomFloat = fc.sample(randomFloatArbitrary, 1, { seed: 42})[0];
console.log(randomFloat);
and that seemed to work just fine too.
Documentation of pure-rand updated at: https://github.com/dubzzz/pure-rand/pull/715