~eda-qa/dhlib/main

« back to all changes in this revision

Viewing changes to lib/mathx/LinearCongruentialGenerator.hx

  • Committer: edA-qa mort-ora-y
  • Date: 2010-02-16 05:36:32 UTC
  • Revision ID: eda-qa@disemia.com-20100216053632-60lt7fndfi3fgblw
first

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* <license>
 
2
 * This file is part of the dis-Emi-A HaXe Library. Copyright © edA-qa mort-ora-y
 
3
 * For full copyright and license information please refer to doc/license.txt.
 
4
 * </license> 
 
5
 */
 
6
package mathx;
 
7
 
 
8
/**
 
9
 * The classic random number generator.
 
10
 * http://en.wikipedia.org/wiki/Linear_congruential_generator
 
11
 */
 
12
class LinearCongruentialGenerator implements RandomGenerator
 
13
{
 
14
        var a : Int;
 
15
        var c : Int;
 
16
        var cur : Int;
 
17
        
 
18
        public function new( a : Int, c : Int, ?seed : Null<Int> = null )
 
19
        {
 
20
                this.a = a;
 
21
                this.c = c;
 
22
                
 
23
                if( seed == null )
 
24
                        cur = Math.round( haxe.Timer.stamp() * 1000 );
 
25
                else
 
26
                        cur = seed;
 
27
        }
 
28
        
 
29
        static public function standard() 
 
30
        {
 
31
#if neko
 
32
                //from Numeric recipes
 
33
                return new LinearCongruentialGenerator( 1664525, 1013904223 );
 
34
#else
 
35
                //from GCC
 
36
                return new LinearCongruentialGenerator( 1103515245, 12345 );
 
37
#end
 
38
        }
 
39
        
 
40
        public function nextFloat() : Float
 
41
        {
 
42
                return nextInt() / Limits.intMax;
 
43
        }
 
44
        
 
45
        public function nextInt() : Int
 
46
        {
 
47
                cur = cur * a + c;
 
48
                return MathUtil.absi( cur );
 
49
        }
 
50
        
 
51
        public function reseed( seed : Int ) : Void
 
52
        {
 
53
                cur = seed;
 
54
        }
 
55
}