Shop OBEX P1 Docs P2 Docs Learn Events
HELP: Generating random numbers in PASM — Parallax Forums

HELP: Generating random numbers in PASM

BeanBean Posts: 8,129
edited 2011-01-20 09:42 in Propeller 1
I got this code from Chip's interpreter.spin
:rnd                    min     x,#1                    '?var/var?
                        mov     y,#32
                        mov     a,#%10111
        if_nz           ror     a,#1
:rndlp                  test    x,a             wc
        if_z            rcr     x,#1
        if_nz           rcl     x,#1
                        djnz    y,#:rndlp       wc      'c=0
                        jmp     #:stack

The "z" flag is set or cleared for a forward or backward random calculation. I only need to do the forward (z set). So I have optimized the code as follows:
                  min           x,#1                     '  RANDOM value
                  mov           y,#32                 
__L0001                                                     
                  test          x,#%10111      WC            
                  rcr           x,#1                    
                  djnz          y,#__L0001     WC         

But it doesn't seem to be working right. If I plot the random values, I get a diamond pattern not a random pattern.

I can't figure out what I am doing wrong.

Bean

Comments

  • BeanBean Posts: 8,129
    edited 2011-01-20 07:46
    Okay, It must be something I'm doing because the PASM code came from Chip. See this thread http://forums.parallax.com/showthread.php?117913-Random-number-in-PASM

    If I want a random number between 0 and x do I just return the "value MOD x" ?

    Bean
  • JonnyMacJonnyMac Posts: 9,208
    edited 2011-01-20 08:33
    Modulus will return a value from 0 to X-1.
  • ericballericball Posts: 774
    edited 2011-01-20 08:58
    Bean wrote: »
    If I want a random number between 0 and x do I just return the "value MOD x" ?
    JonnyMac wrote: »
    Modulus will return a value from 0 to X-1.
    Yes, just be aware that if X is not a power of two there will be a slight bias for the lower values. "value ** x" will also return a value from 0 to X-1 but the bias will be distributed more evenly through the whole range.
  • Bobb FwedBobb Fwed Posts: 1,119
    edited 2011-01-20 09:42
    Bean wrote: »
    If I plot the random values, I get a diamond pattern not a random pattern.

    The random values are not random. If you run a sequence like
    REPEAT
        DEBUG.dec(?val)
    
    You'll get cyclical numbers. You need a real analog input to get a real random number. That's why we have the real random object in the OBEX.
Sign In or Register to comment.