pure-rand icon indicating copy to clipboard operation
pure-rand copied to clipboard

Document float/double algorithms

Open dubzzz opened this issue 1 year ago • 1 comments

How to generate floats or doubles out of an integer value?

Note: We have snippets doing so in fast-check

dubzzz avatar Sep 09 '23 07:09 dubzzz

Yes, please add. Baffling to have a prng library with no way of generating floats.

BorisTheBrave avatar Dec 04 '23 17:12 BorisTheBrave

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?

smohanty92 avatar Jun 26 '24 16:06 smohanty92

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)"

dubzzz avatar Jun 26 '24 17:06 dubzzz

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

smohanty92 avatar Jun 26 '24 18:06 smohanty92

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

dubzzz avatar Jun 26 '24 20:06 dubzzz

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.

smohanty92 avatar Jun 26 '24 20:06 smohanty92

Documentation of pure-rand updated at: https://github.com/dubzzz/pure-rand/pull/715

dubzzz avatar Jun 27 '24 07:06 dubzzz