Shop OBEX P1 Docs P2 Docs Learn Events
Modified RealRandom.spin — Parallax Forums

Modified RealRandom.spin

Jorge PJorge P Posts: 385
edited 2012-08-17 15:52 in Propeller 1
Hi all, I thought this modification to RealRandom.spin would be usefull to alot of you who require random numbers within a certain range. This is more an addition to the origional driver than a modification.

The new function "RealRandom.randomMax(nMax)" will return a number between 0 and nMax-1. without slowing things down too much.

I have included a demo with the attached zip. Hope you enjoy.

Jorge

Comments

  • JonnyMacJonnyMac Posts: 9,108
    edited 2012-08-17 08:56
    Is this not an option because of speed?
    pub randomMax(nMax)
    
      return (random >> 1) // nMax
    
  • Jorge PJorge P Posts: 385
    edited 2012-08-17 09:02
    never thought to use that. but if it works just the same, it would be less code.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2012-08-17 09:33
    The mod (//) operator works fine for small maxima. As the maximum value increases, though, the output will become more skewed for maxima that are not powers of two. Jorge's method, though inefficient, produces non-skewed results.

    Jorge, BTW, you can eliminate your CASE statement completely by using the result of the >| operator to compute the required shift amount.

    -Phil
  • NurbitNurbit Posts: 53
    edited 2012-08-17 10:56
    would it be difficult to add the ability to specify a minimum number too?
    E,g if you want a random number between 10 and 20 ?
  • SRLMSRLM Posts: 5,045
    edited 2012-08-17 15:52
    Nurbit wrote: »
    would it be difficult to add the ability to specify a minimum number too?
    E,g if you want a random number between 10 and 20 ?

    In this case, couldn't you simply specify maximum of 10, and add 10 to the result? That would get you to the correct range.
Sign In or Register to comment.