Shop OBEX P1 Docs P2 Docs Learn Events
Real Random - KISS — Parallax Forums

Real Random - KISS

CassLanCassLan Posts: 586
edited 2008-06-27 22:40 in Propeller 1
I understand this generates a long...but what if I want a random number between··0 and 24?

I was doing (rr.random//24) but I'm not sure this is the way to do this.

Thanks

Rick

Comments

  • LeonLeon Posts: 7,620
    edited 2008-06-27 03:28
    How about dividing by 2^32 to get a random number between 0 and 1 and multiplying by 24, or something like that?

    Leon

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Amateur radio callsign: G1HSM
    Suzuki SV1000S motorcycle

    Post Edited (Leon) : 6/27/2008 3:34:14 AM GMT
  • CassLanCassLan Posts: 586
    edited 2008-06-27 03:42
    OK so I tried that approach:

    x := (rr.random/2^32) * 39

    With the code above, I'm trying to get a number between 0-39, instead I get 0-240 so far.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2008-06-27 03:50
    rr.random // 25 will give you a number between 0 and 24. It's pretty good, but not perfect. If a uniform distribution is important, a better alternative would be:

    repeat
      r := rr.random & 31
    until r < 25
    
    
    


    This is because the // operator, when the divisor is not a power of 2, will give slightly skewed results. However, if nearly perfect statistics are unimportant, the modulo operator — especially for small ranges — is probably good enough.

    -Phil

    Addendum: Here's a method that should yield results quicker than the above:

    repeat
      r := rr.random
    until r < r / 25 * 25
    r //= 25
    
    
    


    This has the same statistics as the first example but throws away far fewer results. Due to the two divisions and one muliplication, though, its advantages diminish as the high end of the range approaches a powwer of two.

    -P.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    'Still some PropSTICK Kit bare PCBs left!

    Post Edited (Phil Pilgrim (PhiPi)) : 6/27/2008 4:21:04 AM GMT
  • LeonLeon Posts: 7,620
    edited 2008-06-27 04:15
    CassLan said...
    OK so I tried that approach:

    x := (rr.random/2^32) * 39

    With the code above, I'm trying to get a number between 0-39, instead I get 0-240 so far.

    You need to use floating point. I should have said multiply by 25 and subtract 1, so you could try mutiplying by 40 and subtracting 1.

    This is the standard technique used with the usual random number functions like that provided with gcc, that generate a number between 0 and 1. It gives a proper uniform random distribution and doesn't 'waste' any numbers.

    Leon

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Amateur radio callsign: G1HSM
    Suzuki SV1000S motorcycle

    Post Edited (Leon) : 6/27/2008 4:33:14 AM GMT
  • CassLanCassLan Posts: 586
    edited 2008-06-27 22:40
    Thanks Both, I decided to do full Long then just do bit shifting to make the number much smaller (BYTE) and then work with it
Sign In or Register to comment.