Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active February 22, 2018 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/c166f03122d0f710f5a497fedd6a8199 to your computer and use it in GitHub Desktop.
Save komasaru/c166f03122d0f710f5a497fedd6a8199 to your computer and use it in GitHub Desktop.
Ruby script to test for uniformity of random number with Chi-square algorithm.
#! /usr/local/bin/python3.6
"""
Test for uniformity of random number with Chi-square algorithm
"""
import math
import sys
import traceback
class Chi2Rndnum:
A = 1103515245 # Multiplier
C = 12345 # Increment
M = 2 ** 31 # Modulus
N = 1000 # Number to generate
M_MAX = 10 # Range of integer random number
F = N / M_MAX # Expectation
S = 40.0 / F # Scale for histgram
def __init__(self):
self.r = 12345
self.hist = [0 for _ in range(self.M_MAX + 1)]
self.e = 0.0
def generate_rndnum(self):
""" Generation of random numbers """
try:
for _ in range(self.N):
self.hist[self.__rnd()] += 1
except Exception as e:
raise
def display(self):
""" Calculation and display """
try:
for i in range(1, self.M_MAX + 1):
print("{:>3}:{:>3} ".format(i, self.hist[i]), end="")
for _ in range(int(self.hist[i] * self.S)):
print("*", end="")
print()
self.e = self.e \
+ (self.hist[i] - self.F) \
* (self.hist[i] - self.F) / self.F
print("Chi-square =", self.e)
except Exception as e:
raise
def __rnd(self):
""" Generation of integer between 1 and 10 """
try:
self.r = (self.A * self.r + self.C) % self.M
return math.floor(self.M_MAX * (self.r / (self.M - 0.9))) + 1
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = Chi2Rndnum()
obj.generate_rndnum()
obj.display()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment