Question

I need a random integer between 0 and an integer with over 1000 decimal places.

Working with integers this large is easy with: big-integer (NPM), but there is no random method, and Math.random() doesn't express enough precision to cover the domain.

Does anyone know a clever way of generating pseudo random integers in a large range in JavaScript?

Was it helpful?

Solution

I think best solution for your case in Node.JS is crypto.randomBytes(size, [callback]);

OTHER TIPS

Perhaps this:

var crypto = require('crypto');
var biformat = require('biguint-format');

// Adjust # bytes as needed
var seed = biformat(crypto.randomBytes(8), 'dec');
bigInt(seed);

https://www.npmjs.com/package/random-bigint

const random = require('random-bigint')

// synchronous api, generates a random number between 0 and 2**128-1
const num = random(128) // 128 bits

FYI, ** is Exponentiation

function genRandomNumber(byteCount, radix) {
  return BigInt('0x' + crypto.randomBytes(byteCount).toString('hex')).toString(radix)
}

// to genrate a 8 byte number in decimal format string
const randomNumber = genRandomNumber(8, 10)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top