![]() |
Random double (inclusive of range)
I'm trying to get a random double number with includes the low and high bound itself.
I've tried: :
Math.random()*(highBound()-lowBound())+lowBound());if i enter say 6 to 10 for low and high bound respectively, i can't get the number 6.0000 and 10.0000. Is it possible to include both ends? |
Math.random should return a number that is greater than or equal to 0, and less than 1. So your lower bound at least, will eventually turn up.
The problem is the 'eventually' part. Doubles are 64 bit types, so there's 2^64 representable values between 1 and 0; that's 1.8e19 in standard form. With this many choices, it'll be a while before you end up with exactly zero, especially considering that there are only 2.4e9 seconds in the average western human lifespan. It's perfectly possible to include both ends, but statistically you won't see them unless you limit the number of values that Math.random can return. Perhaps you only need integers, or perhaps you only need numbers that go down to two decimal places. |
highest = 10
lowest = 6 6 + (int) (Math.random() *10) ;) |
Quote:
Use Math.random() * (10 - 6) instead. |
yeaaaah! Sorry it only works when the lowest number is 1, sorry!
6 + (int) (Math.random() * 10 - 6) |
Quote:
:
6 + (int) (Math.random() * (10 - 6)) |
Yeah, thanks guys.
For getting integers from 6 to 10, i have no problems. It's decimal points from 6.00 to 10.00 that i can't get the both ends. Since Arevos said that the numbers will eventually turn up, i guess there's no problem then. I asked this because i thought that math.random returns a value between 0 to 1, not including 0 and 1. Now i'm confused. |
put (int) in front of the statement, it will turn out with no demicals!
|
Quote:
|
it returns 0 - 0.99999999999999999999, better explanation
|
| All times are GMT -5. The time now is 9:14 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC