Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats wrong with the following code for generating a pseudo-random integer between 0 and n-1?

0
Posted

Whats wrong with the following code for generating a pseudo-random integer between 0 and n-1?

0

int r = (int) (Math.random() * n); // not recommended!! It can be slower than necessary since it performs two int to double conversions and a floating point multiply. Also, Math.random gives you no control over the seed, which is useful for debugging. Nevertheless, we use this approach for simplicity, before we introduce objects and Random. Also, if n is very large, the values produced are far from uniformly random, even if Math.random is.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123