Shop OBEX P1 Docs P2 Docs Learn Events
how do i generate random numbers in an interval? — Parallax Forums

how do i generate random numbers in an interval?

Hi,

Title says all. I know the ? operator but I have no idea how to put it to practical use. Spin doesn't have a random function like I'm used to with other languages so I have no idea how and what to do with "?". Any help would be greatly appreciated.

Cheers!

Comments

  • There is a Random Number Generator in the OBEX:

    http://obex.parallax.com/object/498
  • Type "Random" in the upper right search box and it will bring up some threads about Random generation.
  • Try this in your program:
    VAR
      long seed
    
    PUB random(lo, hi)
      return lo + ?seed // (hi - lo)
    

    It will return a random number between lo and hi - 1.

    -Phil
  • Try this in your program:
    VAR
      long seed
    
    PUB random(lo, hi)
      return lo + ?seed // (hi - lo)
    

    It will return a random number between lo and hi - 1.

    -Phil

    Are you sure that's correct? Don't you need to strip the sign bit before the // in case the result of ?seed is negative? Otherwise, it will return numbers in the range (lo-(hi-lo+1), hi).
  • Don't you need to strip the sign bit ...
    I do that in the prng object that I liberated from @Heater.
    pub randomize(lo, hi) 
    
    '' Return a random number between lo and hi (inclusive)
    
      return  (random >> 1) // ((hi - lo) + 1) + lo
    
    I also try to stick a call to the random() method in a loop so that the prng sequence is constantly being tumbled. The P2 does this for us, providing a new random # on every clock.
  • Are you sure that's correct? Don't you need to strip the sign bit before the // in case the result of ?seed is negative? Otherwise, it will return numbers in the range (lo-(hi-lo+1), hi).
    You're correct, of course. Jon has it right.

    -Phil
  • is there a way to randomize numbers from 1 to 70?
    Thanks

  • @bluejay said:
    is there a way to randomize numbers from 1 to 70?
    Thanks

    In the post above there is discussion about the randomize() method from the attached object. It would go like this:

    rval := prng.randomize(1, 70)

    Easy peasy.

  • Hi

    @bluejay said:
    is there a way to randomize numbers from 1 to 70?
    Thanks

    I wonder if you are asking for all the numbers 1 to 70 to be in a randomised order since getting a random number between 1 and 70 has already been explained.
    If that is the case then build an array with the numbers 1 to 70 in it and starting at array item 1, exchange it with another number in the array, range 1-70 generated using the randomise function, and work your way through the whole array.

    Dave

Sign In or Register to comment.