2

Java Math.random() returns a random number in [0..1). Is there a way to make 1.0 inclusive? Eventually I would like to have a random number (floating point number) in a specific range such as [Min..Max]. We know that for integers it will be

Min + (int)(Math.random() * ((Max - Min) + 1))

I reviewed answers shown below in "Random floating point double in Inclusive Range". Alex L. answer is very close, but it is not quite right as Kendall Prey commented.

function randomInRange(min, max) {
  return Math.random() < 0.5 ? ((1-Math.random()) * (max-min) + min) : (Math.random() * (max-min) + min);
}

To use it in a Monte Carlo simulation application, two boundaries should be either inclusive or exclusive exactly.

Youngsup Kim
  • 2,235
  • 5
  • 13
  • 18
  • 1
    You don't actually want to do this, it doesn't do anything – nhouser9 Sep 27 '16 at 01:34
  • 2
    With a random double the probability of hitting one exact number is actually infinitely small (since there are an infinite number of possible fractions between 0 and 1), which means that in practice even if you changed the random number generator to include 1.0, for all intents and purposes it would never return 1.0. See this: http://stackoverflow.com/questions/2143723/write-a-truly-inclusive-random-method-for-javascript/2143750#2143750 – nhouser9 Sep 27 '16 at 01:35
  • I have found some helpful tips and insight about the same problem as nhouser9 suggested. Thanks for good comments by nhouser9. <> – Youngsup Kim Sep 27 '16 at 02:34
  • But, this is in my coding assignment. I guess I will do it exclusive of 1. Youngsup Kim, did you find a way? –  Jul 17 '22 at 06:01

0 Answers0