pythonrecursionlcg

Python: Not Returning Value From Linear Congruential Generator Function


I am attempting to make a randomly generated plot using the LCG method. While the plot behavior works, my issue is when I attempt to return a list to a variable. My goal is to have the recursive function return a list to a variable, but it seems that it does nothing when it exits the definition.

Recursive Function (inside definition):

def LCG_recursive(vmin, vmax):
    for x in range(0, 1):
        randnum = 19680801      # Fixing random state for reproducibility
        randnum2 = []           # clearing list for next random set
        break
    for x in range(1, i+1):
        randnum = ((a*randnum+b) % M) / M
        randres = (vmax - vmin)*randnum + vmin    #limit to range of plot
        randnum2.append(randres)
        if x>i:
            return randnum2

Called From:

# For each set of style and range settings, plot i random points in the box
# defined [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    
    xs = LCG_recursive(23, 32)
    ys = LCG_recursive(0, 100)
    zs = LCG_recursive(zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

My attempt was to set the seed as randnum and clear randnum2 for every retrieval of a randomly generated list of values. However, attempting to step through the file shows that it performs the recursion successfully, but returns a NoneType object when it moves to the next axis list.

I attempted to create global variables and check to see if I could move randnum2 after I performed the recursive operation, but I haven't gotten any luck.


Solution

  • It actually ended up needing a break statement to force it outside of the second range before it would let me return any values. I did note the removal of the unnecessary for loop for the first few lines. Here is what I came up with:

    def LCG_calc(vmin, vmax):
            
        randnum = 19680801      # Fixing random state for reproducibility
        randnum2 = []           # clearing list for next random set
        
        for x in range(0, n):
            randnum = (a*randnum+b) % M
            randnum = randnum /M
            randres = (vmax - vmin)*randnum + vmin    #limit to range of plot
            randnum2.append(randres)
            if x>n:
                break
            
        return randnum2