Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

algorithm for random number  RSS feed

 
kundan varma
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI All
I dont want to use Math.random but want to implement my own random number logic having upper and lower bound.
Can somebody help me developing a methos like this.
Some hints, some logic
THanks
kundan
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lower + Math.random(upper - lower)? Use Math.floor() if you want integers. Or use lower + new java.util.Random().nextInt(upper - lower). In all cases "upper" is exclusive, i.e. the numbers returned are smaller than the upper bound.

- Peter
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well - why do you want to make your own random-number?
Only to to call it with ?

On linux you may use /proc/sys/random/uuid where you will allways find fresh numbers: 8-4-4-4-12 hexdigits. I didn't search for hints, how to use them seriously - there is a /proc/sys/random/entropy_avail and I don't know how to use that. It's using keyboard and mouse-events to generate the value, and therefore it is nearly impossible, to determine the value in advance, if there is some traffic on these devices.

To get allways different values, you may use the time, which can be ok, if your application calls the random-function only once, but leads to obviously regular values, if called in a loop with constant execution time.

You may reverse the time-values, and concatenate them, and to hide this:

look very regular

look a little more different.
Divide it by an prime, let's say '17':
looks a bit more 'randomly'.
But of course this technique is very poor, and shouldn't be used in serious circumstances.

Most random-generators accept seed-values, and will produce the same sequence of numbers for the same seed.
While this sounds foolish in the first moment, it has the benefit, to make reproducable results - i.e. used for unit-tests.
In real work, you can use the time as seed, for testing you use allways the same seed.

I guess a good random-implementation can be found in src.zip and googling for 'random generator algorithm'.
[ July 26, 2004: Message edited by: Stefan Wagner ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!