You're here: Snippet Directory » Microsoft .NET » C# (33)
Language:

Extension of a Good Random Number Generator Class

Language: English
Programming Language: C#
Published by: jill-eskimo-com [not registered]
Last Update: 5/15/2006
Views: 371

License: Artistic License

Description

This class extends my prior RNDuint class to generate fractions as doubles (0..1), which is generally much more useful than a number between 0 and 2**31 -1 which RNDuint generates.

Code

1 using System; 2 3 namespace Barsoom 4 { 5 /// <summary> 6 /// Good 31-bit Random Number Generator, returns fractions greator than 0 7 /// </summary> 8 public class RNDdouble : Barsoom.RNDuint 9 { 10 protected void doubleCheckSeed(double initialseed) 11 { 12 if ( initialseed >= 1 || initialseed < 0) 13 { 14 throw(new ArgumentOutOfRangeException( 15 "initialSeed", 16 initialseed, 17 "Invalid seed: Must be between 0 and 1") 18 ); 19 } 20 21 uintCheckSeed((uint)(initialseed * (double)m)); 22 } 23 24 public RNDdouble() 25 { 26 // Base constructor is good enough for me! 27 } 28 /// <summary> 29 /// Accepts fractional seed (double) between 0 and 1. 30 /// </summary> 31 /// <param name="initialseed">Value between 0 and 1.</param> 32 public RNDdouble(double initialseed) 33 { 34 doubleCheckSeed(initialseed); 35 } 36 37 /// <summary> 38 /// Get next value or set double. Range 0 to 1. 39 /// </summary> 40 public double d 41 { get 42 { 43 return (double)n/m; 44 } 45 set 46 { 47 doubleCheckSeed(value); 48 } 49 } 50 /// <summary> 51 /// Tests RNDuint then applies bounds testing on fractional seeds. 52 /// </summary> 53 /// <returns>True of compiler implemented this class correctly.</returns> 54 public new bool test() 55 { 56 // First test the LCG it's self. 57 RNDuint t = new RNDuint(); 58 59 if(t.test() == false) 60 return false; 61 62 RNDdouble d = new RNDdouble(); 63 64 // Now test for double seed error 65 // Test 1000 floats 66 try 67 { 68 for(uint i = 1; i < 1000; i++) 69 { 70 d.d = (double)t.n/m; // This'll spew if n/m to big or small 71 72 if( d.n > m) // This is impossible so check for it and make sure it doesn't happen! 73 return false; 74 } 75 } 76 catch( ArgumentOutOfRangeException) 77 { 78 return false; 79 } 80 81 catch 82 { 83 throw; // This'll spew if something very weird happens 84 } 85 86 // Error throw testing 87 try 88 { 89 d.d = 1; // This MUST fail 90 } 91 catch( ArgumentOutOfRangeException e) 92 { 93 // So K 94 return true; 95 } 96 catch 97 { 98 // Not So K 99 return false; 100 } 101 102 return false; // if try did NOT generate an error 103 // then error detection is broken 104 } 105 } 106 } 107

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS