Skip to content

Instantly share code, notes, and snippets.

@kdrnic
Created July 12, 2016 04:43
Show Gist options
  • Save kdrnic/fd69f40073cc04806fbf5124eaf05e67 to your computer and use it in GitHub Desktop.
Save kdrnic/fd69f40073cc04806fbf5124eaf05e67 to your computer and use it in GitHub Desktop.
# test of cc65's rand.s LCG
import math
import random
seed = 1
def srand(x):
global seed
seed = x & 0xFFFF
def rand():
global seed
seed *= 0x01010101
seed += 0x31415927
seed &= 0xFFFFFFFF
return (seed >> 8) & 0x7FFF
def randfunc(a, b):
return a + (rand() % b)
def test_rand(width, iters, rfunc):
count = [0] * width
run_lengths = [[] for i in range(width+1)]
last = width
run = 0
for i in range(0,iters):
v = rfunc(0, width)
count[v] += 1
if v == last:
run += 1
else:
run_lengths[last].append(run)
run = 1
last = v
print("rand() %% %d statistics:" % (width))
for i in range(0,width):
# Perhaps, due to the way run length is tailed, the following should be done?
# Even then, there is a significant difference.
#run_lengths[i] = map(lambda x: math.log(float(x)), run_lengths[i])
avg = float(sum(run_lengths[i]))/float(len(run_lengths[i]))
run_length_sd = math.sqrt(sum(map((lambda x: (avg-float(x))**2), run_lengths[i]))/float(len(run_lengths[i])))
print("%d happened %10d times, average run %.3f run length SD %10.3f" % (i,count[i],avg,run_length_sd))
test_rand(2,100000,randfunc)
test_rand(8,100000,randfunc)
test_rand(2,100000,random.randrange)
test_rand(8,100000,random.randrange)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment