chiSquareTest
authorClaus Gittinger <cg@exept.de>
Wed, 16 Apr 1997 16:49:19 +0200
changeset 518 f5fe8b630e4c
parent 517 4e47b198c9bc
child 519 fc09af1dda59
chiSquareTest
Random.st
--- a/Random.st	Tue Apr 01 23:09:08 1997 +0200
+++ b/Random.st	Wed Apr 16 16:49:19 1997 +0200
@@ -114,6 +114,46 @@
     ^self basicNew setSeed
 ! !
 
+!Random class methodsFor:'testing'!
+
+chiSquareTest   
+    " Chi-Squared Test - from R.Sedgewick's 1st ed. of 'Algorithms', 
+            o N = number of samples
+            o r  = range of random numners is [0,r)      -- condition: N >= 10r.
+            o Random number generator 'passes' if chisquare value is very close to r
+            o Repeat test several times, since it may be *wrong* 1 out of 10 trials."
+
+    | aRand frequencies n range t chisquare |
+
+    chisquare := Array new: 10.     "Collect results from 10 trails"
+    1 to: 10 do: [:k |       "k = trail number"
+        aRand := Random new.  "Seeded differently each time"
+        range := 100.   
+        n := 1000.
+        frequencies := Array new: range.
+        1 to: frequencies size do: [ :i | frequencies at: i put: 0 ].
+        1 to: n do: [ :i |
+                t := ((aRand next) * range) truncated.
+                frequencies at: (t+1) put: ((frequencies at: (t + 1)) + 1) ].
+        t := 0.
+        1 to: range do: [ :i |
+                t := t +  ((frequencies at: i) squared) ].
+        chisquare at: k put: (((range * t  / n) - n) asFloat).
+    ].
+    ^ chisquare
+
+    "
+     Random chiSquareTest 
+    "
+
+    "
+      Sedgewick claims each chisquare number should be 100 +- 20. 
+      The closer to 100, the better.
+    "
+
+    "Modified: 16.4.1997 / 16:48:26 / cg"
+! !
+
 !Random methodsFor:'accessing-reading'!
 
 next
@@ -264,31 +304,6 @@
     ^ false
 !
 
-chiSquare
-    "perform a chiSquare-test on the receiver"
-
-    "returns on Sun3 93.40000000000009"
-    ^self chiSquare: 1000 range: 100
-
-    "Random new chiSquare"
-!
-
-chiSquare: n range: r
-    | f t s |
-    self setSeed. "/ seed := 1234567.
-    f := Array new: r + 1.
-    1 to: r + 1 do: [ :i | f at: i put: 0 ].
-    n timesRepeat:
-        [ self step.
-          t := seed \\ r.
-          f at: t + 1 put: (f at: t + 1) + 1 ].
-    t := 0.
-    1 to: r do: [ :i | t := t + (f at: i) squared ].
-    ^r asFloat * t / n - n
-
-    "Modified: 1.4.1997 / 22:47:35 / cg"
-!
-
 isReadable
     ^ true
 !
@@ -302,5 +317,5 @@
 !Random class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic2/Random.st,v 1.18 1997-04-01 21:09:08 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic2/Random.st,v 1.19 1997-04-16 14:49:19 cg Exp $'
 ! !