Skip to content

Instantly share code, notes, and snippets.

@no1xsyzy
Last active November 26, 2018 02:48
Show Gist options
  • Save no1xsyzy/e984ba98b460b131728fa53f75e249eb to your computer and use it in GitHub Desktop.
Save no1xsyzy/e984ba98b460b131728fa53f75e249eb to your computer and use it in GitHub Desktop.
a test that tests random generating algorithm with an example
#!/usr/bin/env python3
import random
import math
def average(s):
s = list(s)
return sum(s)/len(s)
class randomtest:
_funs = []
@classmethod
def register(cls, expect):
def regis(func):
cls._funs.append((func.__name__, func, expect))
return func
return regis
def __init__(self, testee, probe=None):
testee = list(testee)
if probe is None:
self.testee = testee[1:]
self.probe = testee[:-1]
else:
self.testee = testee
self.probe = list(probe)
self.results = []
self.variance = 0
self.calc()
def calc(self):
self.results = []
self.variance = 0
for n, f, e in self._funs:
r = average(map(f, self.probe, self.testee))
self.results.append((n, r, e))
self.variance += (r - e) ** 2
def __str__(self):
m = "test {n}:\n\texpect: {e}\n\tactual: {r}\n"
return "".join(m.format(n=n, e=e, r=r)
for n, r, e in self.results) + \
"total: {0}".format(self.variance)
def __repr__(self):
return "{name}({testee}, {probe})".format(
name = self.__class__.__name__,
testee = self.testee,
probe = self.probe)
def show_scatter(self):
import matplotlib.pyplot as plt
plt.figure()
plt.scatter(self.probe, self.testee)
plt.show()
@randomtest.register(1/2)
def under_x(x, y):
return y < x
@randomtest.register(1/3)
def under_x2(x, y):
return y < x*x
@randomtest.register(1/4)
def under_x3(x, y):
return y < x**3
@randomtest.register(math.pi/4)
def inside_unit_circle(x, y):
return x * x + y * y < 1
@randomtest.register(math.pi/4)
def inside_inner_circle(x, y):
return (x-0.5)**2+(y-0.5)**2 < 0.5**2
@randomtest.register(1/2)
def under_1_minus_x(x, y):
return y < 1 - x
def createshuff(testlen, testrange, shuff):
a = 0
testee = []
for _ in range(testlen):
a = (a + shuff) % testrange
testee.append(a/testrange)
return testee
def main():
print(average(randomtest(createshuff(1000, 65536, 34429)).variance for i in range(100)))
print(average(randomtest(createshuff(80000, 65536, 1)).variance for i in range(100)))
print(average(randomtest(random.random() for _ in range(1000)).variance for i in range(100)))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment