0

I know how this works in principle:

    (Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);

But if I use this for negative numbers for example: I want to generate random numbers ranging from -30 to -35, I use the same formula:

    (Math.random()*(-30-(-35)+1)+(-35));

But the generated numbers contain -29 too. Is there a way to avoid this ? I found the upper solution in one of the older answered questions, I would like to know why it does not work in this case.

Gabko
  • 1
  • 2
  • I'm not sure if the duplicate handles negative numbers (I don't have time to read it all). If it doesn't, just use `(int)(Math.random()*6)-35` – Eran Jan 07 '16 at 10:15
  • I tried, still with the same result. The formula works fine with the positive numbers, it also generates the negative numbers, but generates also -29, whereas -30 should be the highest. – Gabko Jan 07 '16 at 10:35
  • `(int)(Math.random()*6)` is guaranteed to generate an int number between 0 and 5, so subtracting 35 should give you the range you want. – Eran Jan 07 '16 at 10:39
  • I tried `(int)(Math.random()*6)`, as suggeted and it really does generate numbers between 0 and 5. However if I use `(int)(Math.random()*6 -35)` it generates numbers between -29 and -34. I find this strange. If I use `(int)(Math.random()*6 -36)` instead, then I get numbers between -30 and -35. I can´t figure this out – Gabko Jan 07 '16 at 11:02
  • You should note that my comment suggested to cast to int before you subtract 35 - `(int)(Math.random()*6)-35` - that's not what you did. When you cast to int after the subtraction, you might cast a value such as 5.999999-35==-29.0000001 to int, which would give you -29. On the other hand, if you first cast 5.999999 to int, you'll get a 5 and after subtracting 35 you'll get -30. – Eran Jan 07 '16 at 11:09
  • I thought I replied earlier. I came back after a long time and saw I did not answer you. Thank you, your solution works and thanks to your explanation I understand the cause. Thank you – Gabko Jan 26 '16 at 15:19

0 Answers0