TweetFollow Us on Twitter

Random Cocoa

Volume Number: 22 (2006)
Issue Number: 3
Column Tag: Programming

Random Cocoa

Implementing Five PRNG Algorithms in Cocoa.

by Jose R.C. Cruz


Random numbers are commonplace in the field of software design. They are often used in such applications as cryptography, statistics, and simulations. However, the digital computer is a deterministic machine. It executes specific software instructions in a specific order on data usually provided by the user. Some high-end systems use additional hardware to generate random numbers. These generators use natural events such as radioactive decay or thermal noise as a source for randomness. However, most systems nowadays, use algorithms known as pseudo-random number generators (PRNG).

This article will focus on five commonly known PRNG algorithms. A brief background on each algorithm will be presented, focusing on their respective traits and limitations. Later on, a core Cocoa class will be proposed for implementing each PRNG algorithm. Finally, three test algorithms will be presented. These algorithms are used to determine that a PRNG algorithm is generating a statistically acceptable random sequence.

To further assist software engineers in designing and implementing PRNG Cocoa classes, a demo application known as DiceC is developed to accompany this article. This application implements many of the concepts presented here. Both the application and the XCode project are available for downloading at the MacTech web site

The Pseudo-Random Number Generator

Basic Concepts

Pseudo-Random Number Generators are algorithms used to generate number sequences that have the appearance of randomness. They achieve this through the use of an iterative mathematical function and/or bit shifting.

As its name implies, PRNGs are not true random number generators. First of all, they all require an initial numeric value known as a seed. The seed value determines the numbers that will be generated in the sequence. Using the same seed will always result in to the same random sequence. This trait, known as repeatability, is desirable in many applications such as cryptography.

Another aspect of PRNG algorithms is that the random sequence repeats itself after X number of values. This trait, known as a period, is a distinguishing factor between PRNG algorithms. A well-designed algorithm should have a period as close to (if not greater than) the largest possible random value. A 32-bit PRNG, for example, should be able to generate close to 232 random numbers before the sequence repeats itself.

The Middle Square Method

The Middle Square Method (MSM) is one of the earliest known PRNG algorithms devised for the digital computer. It was proposed by Dr. John von Neumann and used on the ENIAC computer in 1946. It is also a poor generator; its inclusion in this article is mainly for comparative purposes.

Figure 1 shows the generating function used by the MSM algorithm. When generating a new random number, the previous number is first squared. Then only those digits located in the relative middle of the squared result are retrieved as the next random value. The number of significant digits of each random value matches those that comprise the seed value.

To illustrate, if the seed has a value of 1234, first calculate the square of the seed.

1234^2 =????????

The first random number would then be the middle 4 digits of the squared result.

mid(1522756)= 5227

To generate the second random number, simply take the first random number and follow the same two steps as shown above.

5227^2 = 27321529
mid(27321529) = 3215

The MSM algorithm has a number of shortcomings. One is that the algorithm suffers from a very short period of 10m, where m is the number of significant digits contained by the seed value. In the above example, the seed value only has 4 significant digits. This implies that the algorithm can theoretically generate no more than 9999 unique numbers before it repeats the entire sequence.

Another shortcoming is that the MSM algorithm sometimes implodes into a non-random sequence long before it reaches its maximum period. Unless it is provided with a new seed, the algorithm will start generating a small handful of single number values.

Figure 1. The Middle Square Method.

The Linear Feedback Shift Register

The Linear Feedback Shift Register (LFSR) algorithm uses bit taps and bit shifting to generate a random sequence. As shown in Figure 2, the algorithm first taps specific bits off a theoretical register. It then determines the odd parity of the tapped bits by using an XOR operation. The contents of the register are shifted to the left by one, and the most significantn bit (msb) replaced is by the computed parity bit.

The LFSR algorithm is fast, simple and reliable. It has a maximum theoretical period of 2m, where m is the bit precision of the register. The 32-bit example shown in Figure 2 has a maximum theoretical period of 232. This implies that up to 4 294 967 values can be generated before the random sequence repeats itself.

Due to its simplicity, the LFSR is often implemented as a hardware generator. It has found popular usage in embedded systems such as spread-spectrum radio and GPS units. Non-linear variants of the LFSR algorithm were also used in cryptography for generating stream ciphers.

Figure 2. The Linear Feedback Shift Register.

The Linear Congruential Generator

The Linear Congruential Generator (LCG) is one of the oldest and most widespread PRNG algorithms. Many modern operating systems and code libraries use a variation of this algorithm as their random number generator.

Unlike the previous two, the LCG algorithm uses a modular equation (Figure 3) to generate a random sequence. Its overall performance is strongly depended on values chosen for its generator constants A, B and M. A list of common LCG variants, and their respective generator constants, is shown in Table 1.

To ensure an optimal period, the following rules are usually followed when choosing values for the three generator constants:

  • Constant A is a positive integer much greater than 1.
  • Constants B and M needs to be relatively prime with each other. In other words, they share no common factors except 1. This does not imply that either B or M (or both) have to be prime numbers
  • The expression (A - 1) should be divisible by all prime factors of M. Consequently, if M happens to a multiple of 4, then (A - 1) should also be a multiple of 4.
  • The constant M should be greater than the constants A and B, and the seed value, R0.

To determine if constants B and M are relatively prime, the algorithm known as Euclid's Algorithm is used. This algorithm employs successive modular divisions to determine the greatest common denominator (GCD) shared by two integers. If the integers are relatively prime, they will have a GCD of 1. An implementation of Euclid's Algorithm as an ObjC method is shown in Listing 1.

Table 1. List of common LCG variants.

Figure 3. The Linear Congruential Generator.

Listing 1. Euclid's Algorithm implemented as an ObjC method.

- (BOOL)isValue:(unsigned int)argA
                        relativelyPrimeTo:(unsigned int)argB
   BOOL chk_flg;
   unsigned int loc_a, loc_b, loc_r;
   // initialize the following locals
   loc_a = (argA > argB) ? argA : argB;
   loc_b = (argA > argB) ? argB : argA;
   // run Euclid's Algorithm
   while (loc_b != 0)
      loc_r = loc_a % loc_b;
      loc_a = loc_b;
      loc_b = loc_r;
   // check the last non-zero remainder
   chk_flg = (loc_a == 1);
   // return the check results
   return (chk_flg);

The Lagged Fibonacci Generator

The Lagged Fibonacci Generator (LFG) is a specialized version of the LCG algorithm. It uses the Fibonacci sequence of Sn*Sn-1 to generate its pseudo-random sequence. Unlike other PRNG algorithms, the LFG algorithm uses an initialization vector containing multiple seed values. The vector is often initialized using a different PRNG algorithm. Also, the LFG algorithm uses its random sequence to update its initialization vector, thus improving the overall periodicity of the algorithm.

The generating function of the LFG algorithm is shown in Figure 4. The base modulus, M, is usually assigned a value of 2m, where m is the integer bit size. The token o indicates the binary operator used by the algorithm. This can be any of the following primitives: addition (+), multiplication (x) or exclusive-OR (?). The choice of operator also categorizes the LFG algorithm being used. If the algorithm uses an additive or a multiplicative operator, it is referred to respectively as an Additive or Multiplicative LFG. If an XOR operator is used, the algorithm is referred to as a Two-Tap Generalized Shift Feedback Register (GSFR).

The choice of operator also dictates the theoretical period of the LFG algorithm. If an additive or XOR operator is used, the algorithm has a theoretical period of (2k - 1 )*2M-1. If a multiplicative operator is used, the theoretical period becomes (2k - 1)*2M-3, which is 1/4 the period of the additive and XOR version.

Figure 4. The Lagged Fibonacci Generator.

The Blum Blum Shub Algorithm

The Blum Blum Shub (BBS) algorithm was developed in 1986 by Lenore and Manuel Blum, together with Michael Shub, as a secure PRNG for cryptographic applications. This algorithm can also be used for simulation projects; however, performance issues render it unattractive for such applications.

The generating function of the BBS algorithm is shown in Figure 5. The generator constant, M, is derived as a product of two prime numbers, p and q. For optimal performance, the following guidelines are proposed when choosing values for p and q:

  • Both p and q should be congruent to the modulus 3 mod 4. In other words, dividing either p or q by 4 should always result in a remainder of 3.
  • The GCD of the expressions (p-1) and (q-1) should be as small as possible to guarantee a large period.

Unlike the previous PRNGs, only the least significant bits of Rn+1 are used as the next random value. This ensures that the random sequence is resistant to linear cryptanalysis. For optimal security, it is proposed that no more than log(log(M)) bits of Rn+1 should be extracted and used as part of the random sequence.

Figure 5. The Blum Blum Shub algorithm.

The PRNG Cocoa Classes

The Class Structure

The UML diagram of the proposed PRNG Cocoa class structure is shown in Figure 6. The core class, RandBase, provides the code foundation that will be used by 5 other subclasses. Each subclass implements one of the PRNG algorithms covered in this article.

Figure 6. UML diagram of the PRNG class structure.

Figure 7 is the UML diagram of the RandBase core class. For purposes of clarity, I use the more familiar ObjC syntax (as opposed to the standard UML convention) in describing the properties and methods contained by each class.

Three NSString properties store information describing the PRNG class. These are modified using the setDescription:toString method. The information stored is then displayed using the description method.

The prngSeed property stores the seed value used by the PRNG algorithm. Casting it as a generic datatype, id, allows the flexibility to use any Cocoa object as a potential seed. This property is initialized by the core class using either the initWithValue or initWithUnsignedInt methods.

The prngValue property stores the current random value generated by the PRNG algorithm. It is initially set to the same value as prngSeed through the placeholder method, initModelOnReset. This property is casted as an NSNumber so that the random value can be represented in any one of the following datatypes: string, unsigned integer, double, etc. This property is accessed and modified respectively using the randomValue and setRandomValue methods.

The placeholder method, initModelOnReset, contains the initialization code unique to the PRNG algorithm. Each of the RandBase subclasses overload this method to set their own description strings, default seed values and generator constants.

The placeholder method, generate, contains the actual PRNG algorithm. This is also where the actual numeric value of the seed is determined. The RandBase subclasses overload this method with their own implementations. In the core class, this method defaults to the BSD library function, rand(), as the random number generator. Also, the generator is initialized in the initModelOnReset method using the last random number generated by rand().

Regardless of what algorithm is used, the generate method saves the new random number using the setRandomValue method. It also returns the random number as an NSNumber.

Figure 7. The RandBase core class.

All of the RandBase subclasses proposed in this article will generate random sequences of 32-bit unsigned integers. Support for other numerical datatypes (64-bit, signed, etc.) can be accomplished by simply modifying each subclass.

The RandMSM Subclass

Figure 8 shows the UML diagram of the RandMSM subclass. This subclass contains the NSRange property, msm_mask, which stores the position and length of the middle-value mask. The contents of this property are accessed using the setMask and maskValue methods.

The overloaded method, generate, implements the MSM algorithm as shown in Listing 2. This method first retrieves the previous random value and calculates its square product in 64-bit precision. It then converts the resulting 64-bit value to an NSString.

If a middle-value mask has been defined, the method retrieves the mask and applies it to the NSString data. Otherwise, it uses the string length to make a best-guess estimate of the middle value range. The extracted substring is then converted to a 32-bit unsigned integer.

Figure 8. The RandMSM Subclass.

Listing 2. The [generate] method (RandMSM.m).

- (NSNumber *)generate
   NSString   *str_val;
   NSRange   old_msk, new_msk;
   BOOL      str_chk;
   unsigned int   str_pos, str_max, str_len, ui32_val;
   unsigned long long   ui64_val;
   // initialize the following locals
   ui64_val = [[super randomValue] unsignedLongLongValue];
   ui64_val = ui64_val * ui64_val;
   str_val = [NSString stringWithFormat:@"%qu", ui64_val];
   old_msk = [self maskValue];
   str_max = [str_val length];
   // determine the default MSM mask settings
   str_len = str_max / 2 + (str_max % 2);
   str_pos = str_len / 2;
   // validate the current  mask settings
   if (old_msk.location != old_msk.length)
      // use the current mask settings
      new_msk.location = (old_msk.location > str_max) 
         ? str_pos : old_msk.location;
      new_msk.length = (old_msk.length > str_max) 
         ? str_len : old_msk.length;
      // use the default mask settings
      new_msk = NSMakeRange(str_pos, str_len);
   // extract the middle value
   str_val = [str_val substringWithRange:new_msk];
   ui32_val = [str_val intValue];
   // save the new random number
   [super setRandomValue:ui32_val];
   // return the new random number
   return ([super randomValue]);

The RandLFSR Subclass

The UML diagram of the RandLFSR subclass is shown in Figure 9. This subclass contains one private property, lfsr_taps[], which is an array of 32 BOOL datatypes. Contents of this property are accessed using the setTapAtIndex and isTapSetAtIndex methods.

The overloaded method, generate, implements the LFSR algorithm (Listing 3). The method first retrieves the previous random value as well as the tap mask. It applies the mask to the random value thus isolating the desired bits. The msb is then determined by computing the odd-parity of the tapped bits. Afterwards, the previous random value is then shifted to the left by one bit, and the msb applied to the shifted result.

Figure 9. The RandLFSR Subclass.

Listing 3. The [generate] method (RandLFSR.m).

- (NSNumber *)generate
   unsigned int old_val, new_val, msk_val;
   unsigned int bit_pos, bit_val, bit_msb;
   // initialize the following locals
   old_val = [[super randomValue] unsignedIntValue];
   msk_val = [self getTapMask];
   // determine the masked bit values
   msk_val = old_val & msk_val;
      // determine the bit parity [odd-parity of 1]
   bit_msb = 0x0;
   for (bit_pos = 0; bit_pos < LFSR_MAX; bit_pos++)
      bit_val = 0x1 & msk_val;
      bit_msb = (bit_msb == bit_val) ? 0x0 : 0x1;
      msk_val = msk_val >> 0x1;
   // update the current random value
   new_val = old_val >> 0x1;
   bit_msb = bit_msb << (LFSR_MAX - 1);
   new_val = new_val | bit_msb;
   // save the new random number
   [super setRandomValue:new_val];
   // return the new random number
   return ([super randomValue]);

The RandLCG Subclass

Figure 10 shows the UML diagram of the RandLCG subclass. This subclass contains three properties (lcg_a, lcg_b and lcg_m) to store the generator-specific constants of the algorithm. The contents of these properties are modified by the setConstA:ConstB:ConstM method, and are accessed by the methods: getConstA, getConstB and getConstM.

The overloaded method, generate, implements the LCG algorithm as shown in Listing 4. The method first retrieves the previous random value as well as the generator-specific constants. It then calculates the LCG generator function shown in Figure 3 at 64-bit precision. The modulus operation, however, is performed at 32-bit precision, resulting into the new random value.

The checkForError function checks to see if the subclass will generate a random sequence with an optimal period. If so, it returns an Err_None; otherwise, it returns the appropriate error flag. The isValue:divisibleByFactorsOf function returns a YES if the specified numbers share the same prime number factors. Finally, the isValue:relativelyPrimeTo function (Listing 1) performs Euclid's Algorithm on the specified numbers. It returns a YES if both numbers are relatively prime. Both functions work in conjunction with the utility function, checkForError.

Figure 10. The RandLCG Subclass.

Listing 4. The [generate] method (RandLCGm).

- (NSNumber *)generate
   unsigned long long ui64_val, ui64_a, ui64_b;
   unsigned int ui32_val, mod_val;
   // initialize the following locals
   ui64_val = [[super randomValue] unsignedLongValue];
   ui64_a = [self getConstA];
   ui64_b = [self getConstB];
   mod_val = [self getConstM];
   // calculate the next random value
   ui64_val = ui64_val * ui64_val;
   ui64_val = ui64_val + ui64_b;
   ui32_val = ui64_val % mod_val;
   // save the new random number
   [super setRandomValue:ui32_val];
   // return the new random number
   return ([super randomValue]);

The RandLFG Subclass

The UML diagram of the RandLFG subclass is shown in Figure 11. This subclass contains two properties (lfg_p and lfg_q) to store the generators-specific constants to be used by the algorithm. It also contains the private property, lfg_ops, which determines the binary operator to be used. The contents of these properties are modified by the setConstP:constQ:opCode and are accessed by the methods: getConstP, getConstQ and getOpCode.

The RandLFG subclass also maintains the initialization vector in the form of the NSMutableArray property, lfg_vec. Another property, lfg_lim, contains the maximum size that the vector is allowed to grow. Lastly, the lfg_cnt property, keeps track of the number of random values generated by the subclass. It is used to determine which entry in the initialization vector will be updated.

The overloaded method, generate, implements the LFG algorithm (Listing 5). The method first retrieves the previous random value as well as the generators-specific constants. It then determines which seed value to retrieve from the initialization vector. The method calculates the next random value at 64-bit precision, using the selected binary operator. It then updates the initialization vector with the 32-bit result. This is the only subclass that does not save the new random value using the setRandomValue method.

Figure 11. The RandLFG Subclass.

Listing 5. The [generate] method (RandLFG.m).

- (NSNumber *)generate
   unsigned int   idx_p, idx_q, vec_lim, ui32_val;
   unsigned long long   ui64_p, ui64_q;
   unsigned long long   ui64_val, ui64_and, ui64_or;
   LFG_OPCODE arg_ops;
   // validate the initialization vector
   if ([super isSeeded])
      // initialize the following locals
      idx_p = [self getConstP];
      idx_q = [self getConstQ];
      vec_lim = [self getVectorSize];
      arg_ops = [self getOpCode];
      // calculate the vector indices
      idx_p = lfg_cnt - idx_p;
      idx_p = idx_p % vec_lim;
      idx_q = lfg_cnt - idx_q;
      idx_q = idx_q % vec_lim;
      // retrieve the values at the specified indices
      ui64_p = [self getValueAtIndex:idx_p];
      ui64_q = [self getValueAtIndex:idx_q];
      // calculate the next state value
      switch (arg_ops)
         case lfgAdd:
            // -- prng:LFG:additive
            ui64_val = ui64_p + ui64_q;
         case lfgMul:
            // -- prng:LFG:multiplicative
            ui64_val = ui64_p * ui64_q;
         case lfgXOR:
            // -- prng:LFG:XOR
            ui64_and = ui64_p & ui64_q;
            ui64_or = ui64_p | ui64_q;
            ui64_val = ui64_or & ~(ui64_and);
      // include the modulus base
      ui32_val = (unsigned int)(ui64_val % DFLT_BASE);
      // update the initialization vector
      idx_p = lfg_cnt % vec_lim;
      [self setValue:ui32_val atIndex:lfg_cnt];
      // save the new random number
      [super setRandomValue:ui32_val];
      // return the new random number
      return ([super randomValue]);
      // return the current seed value
      return ([super seedValue]);

The RandBBS Subclass

Figure 12 shows the UML diagram of the RandBBS subclass. This subclass contains two properties (bbs_p and bbs_q) to store the prime constants, p and q. It uses the property, bbs_m, to store the generator constant M. The subclass also has the property, bbs_mask, which is the user-defined bit mask used to extract the new random value. Finally, it has the BOOL property, bbs_opt, dictating whether to use the user-defined bit-mask or the optimal one discussed earlier in this article. All of these properties are accessed by their respective methods.

The overloaded method, generate, implements the BBS algorithm as shown in Listing 7. The method first retrieves the previous random value and the base modulus, M. It calculates the square of the random value at 64-bit precision, and then determines the modulus result at 32-bit precision. Afterwards, the method applies the appropriate bit mask to the modulus result. It then repeats all of the aforementioned steps until a full 32-bit random value is formed.

By default, the subclass uses the optimal bit mask to extract the bits that will comprise the new random value. The methods, optimalMaskLength and optimalMaskValue (Listing 6), are used to determine the optimal bit mask. However, the subclass can also use a user-defined bit mask. This is done by setting the bit mask using the setMask method and passing a NO to the useOptimalMask method.

Figure 12. UML Diagram of the RandBBS Subclass.

Listing 6. Calculating the optimal bit mask (RandBBS.m).

// -- Calculate the number of bits in the optimal mask
- (unsigned int)optimalMaskLength
   unsigned int ui32_len;
   double dbl_val;
   // calculate the optimal mask length
   dbl_val = (double) [self getBaseModulus];
   dbl_val = log(dbl_val);
   dbl_val = log(dbl_val);
   ui32_len = ceil(dbl_val);
   // return the calculation results

// -- Calculate the optimal BBS mask value
- (unsigned int)optimalMaskValue
   unsigned int ui32_len, ui32_msk, ui32_bit;   
   // calculate the optimal mask value
   ui32_len = [self optimalMaskLength];
   ui32_msk = 0x0;
   for (ui32_bit = 0; ui32_bit < ui32_len; ui32_bit++)
      ui32_msk = ui32_msk | 0x1;
      ui32_msk = ui32_msk << 0x1;
   ui32_msk = ui32_msk >> 0x1;
   // return the calculation results
   return (ui32_msk);

Listing 7. The [generate] method (RandBBS.m).

- (NSNumber *)generate
   unsigned long long ui64_val;
   unsigned int ui32_val, ui32_mod;
   unsigned int ui32_msk, msk_len, msk_cnt, msk_max;
   // initialize the following locals
   ui64_val = [[super randomValue] unsignedLongValue];
   ui32_mod = [self getBaseModulus];
   // is an optimal mask requested?
   if ([self isMaskOptimal])
      msk_len = [self optimalMaskLength];
      ui32_msk = [self optimalMaskValue];
      msk_len = [self getMaskLength];
      ui32_msk = [self getMaskValue];
   // calculate the new random value
   msk_max = 32 / msk_len;
   ui32_val = 0x00;
   for (msk_cnt = 1; msk_cnt <= msk_max; msk_cnt++)
      // calculate the next random value
      ui64_val = ui64_val * ui64_val;
      ui64_val = ui64_val % ui32_mod;
      ui32_val = ui32_val | (ui64_val & ui32_msk);
      if (msk_cnt < msk_max)
         ui32_val = ui32_val << msk_len;
   // save the new random number
   [super setRandomValue:ui32_val];
   // return the new random number
   return ([super randomValue]);

Testing the PRNG Subclasses

A variety of algorithms are available for testing the efficacy of PRNG implementations. These algorithms examine the generated random sequence to determine whether a PRNG is properly configured. They also determine whether or not the generated sequence is statistically suitable for the task at hand.

PRNG test algorithms range from the elegantly simple Lempel-Ziv to the mathematically oriented maximum-of-t test. They all require a large number of random values in order to be effective. A large sample size helps reveal indications of poor randomness such as skewing ness. In fact, it is quite common to have a PRNG generate at least 1000 random values for testing purposes.

This article introduces three simple and effective test algorithms: Lempel-Ziv, Run Method, and Spectral Method. The demo application, DiceC, uses the Spectral Method as its test algorithm.

The Lempel-Ziv Method

The Lempel-Ziv method is one of the simplest test algorithms for a PRNG. In its most basic form, the PRNG in question first outputs its random sequence into a binary file. This file is then compressed using the LZ algorithm or any of its variants. Some implementations do away with file I/O by compressing the random sequence directly in the memory.

Since the LZ algorithm works by identifying and consolidating byte patterns, a pure random sequence should have a near-zero compression ratio. The compression ratio of PRNG random sequence, however, should be very low if it has a near optimal period. Higher compression ratios are often good indications of non-random patterns present in the sequence.

The Lempel-Ziv method is an effective baseline test when comparing various PRNG algorithms. It is also useful for fine-tuning algorithms such as LCG or LFG, whose overall performance is strongly depended on its generator constants or seed values.

The Run Method

The Run method converts a random sequence into a series of states. An ascending state is where each subsequent random value increases with respect to time. It is represented by a (+) sign. The opposite would be a descending state, which is represented by a (-) sign. If the values remain unchanged, the state is considered to be neutral and is represented by a (0).

To illustrate, the random sequence

255 758 029 974 984 320 583 765

has the following random values exhibit an ascending state:

255 -" 758    029 -" 974    974 -" 984
320 -" 583    583 -" 765

whereas the following exhibit a descending state.

758 -" 029      984 -" 320

This reduces the random sequence to the following state sequence

+ - + + - +    +

Once the state sequence is determined, it becomes a simple matter of examining the sequence for any patterns. Long successions of one or more states are undesirable as they indicate a numerical bias in the PRNG random sequence.

The Spectral Method

The Spectral Method divides a random sequence into specific intervals (sometimes known as a spectral period) and then plots the number values within each interval as a scatter graph. The result is a spectrum of data points that can then be examined for patterns.

Figure 13 shows a typical spectrum graph for the BSD rand() function. The random sequence consists of 1000 32-bit unsigned integers. It is generated using a seed value of 0x1ebbccf. The scatter graph is then drawn using a spectral period of 200 values.

Figure 13. Spectral graph of the BSD rand() function.

Notice that the data points are well distributed across the resulting graph. There are no areas where the data points would cluster together forming a pattern. Now, compare this with the spectrum graph for the RandMSM subclass(Figure 14). The random sequence of 1000 integers used in this graph is generated with a seed value of 0x457. Notice the 6 dashed lines located at the bottom of the graph. This indicates that the sequence converged to 6 distinct values after 11 iterations. This is an undesirable trait, especially considering that the implemented MSM algorithm is expected to have a period of 9999 values.

Figure 14. Spectral graph of the MSM generator.

The spectrum graph for the other three subclasses fared much better by comparison. Shown in Figure 15 is the spectrum graph for the RandLFSR subclass. Its random sequence is generated using a seed value of 0xbeef. Like that of the BSD rand() function, the graph shows well-distributed data points with no noticeable patterns.

Figure 15. Spectral graph of the LFSR generator.


The ability to generate random sequences is an essential component of any software code library. Since digital computers are deterministic machines, the only feasible way of generating random sequences is through the use of a pseudo-random number generators or PRNGs. Five different PRNG algorithms are then introduced and discussed.

Later, the class, RandCore, is proposed to serve as the basis for developing a PRNG Cocoa object. Five different subclasses are then based off the RandCore class, with each subclass implementing one of the five PRNG algorithms. Both RandCore and its five subclasses are implemented in the demo application, DiceC. Also, introduced are three test algorithms for testing the PRNG subclasses. One of these algorithms, the Spectral Method, is implemented in DiceC to evaluate the performance of RandCore and its five subclasses.

Bibliography and References

Harvey Gould, Jan Tobochnik, Wolfgang Christian. Random Number Sequences. An Introduction to Computer Simulation Methods. pp.245-249. PDF document posted on 2005 May 19. (c) 2005 Gould, Tobochnik and Christian.

Makoto Matsumoto, Takuji Nishimura. Mersenne Twister:A 623-dimensionally equidistributed uniform pseudorandom number generator. ACM Transactions on Modeling and Computer Simulations:Special Issue on Uniform Random Number Generation. 1998.

Karl Entacher, Hannes Leeb. Inversive Pseudo-random Number Generators:Empirical Results. Parallel Numerics 95. Department of Mathematics. University of Salzburg, Austria. 1995 Sep 27-29.

Jagannath Pisharath. Linear Congruential Number Generators. Newer Math. 2003 Sep.

Martin Geisler, Mikkel Kroigard and Andreas Danielsen. About Random Bits. 2004 Dec 03.

Wikipedia. Euclid's Algorithm. In Wikipedia, the free encyclopedia. The Wikipedia Community, Oct 2005. Online:

Wikipedia. Pseudorandom number generator. In Wikipedia, the free encyclopedia. The Wikipedia Community, Oct 2005. Online:

JC is a freelance engineering consultant currently residing in North Vancouver, BC. He divides his time between custom application development for OS X, technical writing, and teaching origami to children at the local district libraries.


Community Search:
MacTech Search:

Software Updates via MacUpdate

Eye Candy - 30 professional Pho...
Eye Candy renders realistic effects that are difficult or impossible to achieve in Photoshop alone, such as Fire, Chrome, and the new Lightning. Effects like Animal Fur, Smoke, and Reptile Skin are... Read more
Microsoft Office 2016 15.31 - Popular pr...
Microsoft Office 2016 - Unmistakably Office, designed for Mac. The new versions of Word, Excel, PowerPoint, Outlook and OneNote provide the best of both worlds for Mac users - the familiar Office... Read more
Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
QuickBooks R13 - Financial...
QuickBooks helps you manage your business easily and efficiently. Organize your finances all in one place, track money going in and out of your business, and spot areas where you can save. Built for... Read more
Dash 4.0.1 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
Tinderbox 7.0.0 - Store and organize you...
Tinderbox is a personal content management assistant. It stores your notes, ideas, and plans. It can help you organize and understand them. And Tinderbox helps you share ideas through Web journals... Read more
Apple Remote Desktop Client 3.9 - Client...
Apple Remote Desktop Client is the best way to manage the Mac computers on your network. Distribute software, provide real-time online help to end users, create detailed software and hardware reports... Read more
Sparkle 2.1.1 - $79.99
Sparkle will change your mind if you thought building websites wasn't for you. Sparkle is the intuitive site builder that lets you create sites for your online portfolio, team or band pages, or... Read more
1Password 6.5.5 - Powerful password mana...
1Password is a password manager that uniquely brings you both security and convenience. It is the only program that provides anti-phishing protection and goes beyond password management by adding Web... Read more
WhatRoute 2.0.15 - Geographically trace...
WhatRoute is designed to find the names of all the routers an IP packet passes through on its way from your Mac to a destination host. It also measures the round-trip time from your Mac to the router... Read more

Slay your way to glory in idle RPG Endle...
It’s a golden age for idle games on the mobile market, and those addictive little clickers have a new best friend. South Korean developer Ekkorr released Endless Frontier last year, and players have been idling away the hours in the company of its... | Read more »
Tiny Striker: World Football Guide - How...
| Read more »
Good news everyone! Futurama: Worlds of...
Futurama is finding a new home on mobile in TinyCo and Fox Interactive's new game, Futurama: Worlds of Tomorrow. They're really doing it up, bringing on board Futurama creator Matt Groening along with the original cast and writers. TinyCo wants... | Read more »
MUL.MASH.TAB.BA.GAL.GAL 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: ENDLESS UPGRADES. CONSTANT DANGER. ANCIENT WISDOM. BOUNCY BALLS. Launch Sale, 40% OFF for a very limited time!!! MUL.... | Read more »
Dungeon Rushers (Games)
Dungeon Rushers 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Dungeon Rushers is a 2D tactical RPG combining dungeon crawler’s gameplay and turn based fights. Manage your team, loot dusty... | Read more »
Blasty Bubs is a colorful Pinball and Br...
QuickByte Games has another arcade treat in the works -- this time it's a mishmash of brick breaking and Pinball mechanics. It's called Blasty Bubs, and it's a top down brickbreaker that has you slinging balls around a board. [Read more] | Read more »
Corsola and Heracross are the new region...
Generation 2 finally launched in Pokémon GO, unleashing a brand new batch of Pokémon into the wild. Even before the update went live people were speculating on how to catch elusive Pokémon like the legendary "dogs", Unknown, and whether or not... | Read more »
The Warlock of Firetop Mountain (Games)
The Warlock of Firetop Mountain 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: An epic adventure through a mysterious mountain filled with monsters, magic and mayhem! “ looks downright... | Read more »
Fantasy MMORPG MU Origin’s receives a hu...
Developer Webzen are looking to take their highly popular fantasy battler MU Origin to the next level this month, with its most ambitious overhaul yet. The latest update introduces the long sought after Server Arena, new treasure dungeons, and much... | Read more »
RPG Djinn Caster (Games)
RPG Djinn Caster 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: SPECIAL PRICE 38% OFF(USD 7.99 -> USD 4.99)!!!A Fantasy Action RPG of far foreign lands! Summon the Djinns and rise to... | Read more »

Price Scanner via

Apple restocks refurbished 11-inch MacBook Ai...
Apple has Certified Refurbished 11″ MacBook Airs (the latest models recently discontinued by Apple), available for up to $170 off original MSRP. An Apple one-year warranty is included with each... Read more
Apple Park Opens to Employees in April With T...
Apple has announced that Apple Park, the company’s new 175-acre campus, will be ready for employees to begin occupying in April. The process of moving more than 12,000 people will take over six... Read more
Manhattan Neighbors for Safer Telecommunicati...
A new education and advocacy group focused on cell phone and wireless risks, Manhattan Neighbors for Safer Telecommunications, launched today at Manhattan... Read more
Portable Dual DisplayPort Monitor Dock Enable...
IOGEAR has announced the launch of its USB-C Dual DisplayPort Monitor Portable Dock (GUC3CMST). The dock enables users to easily connect two DisplayPort monitors to a USB-C or Thunderbolt 3 laptop to... Read more
13-inch 2.7GHz Retina MacBook Pro on sale for... has restocked the 13″ 2.7GHz/128GB Retina MacBook Pro (MF839LL/A) for $200 off MSRP including free shipping: - 13″ 2.7GHz/128GB Retina MacBook Pro: $1099 $200 off MSRP This model tends to... Read more
Apple’s New iPad Ads Don’t Address Pro Users’...
Apple launched a new tranche of iPad Pro TV ads last week addressing actual queries and challenges from the Twitterverse, albeit using actors for the visuals. That’s great. As an iPad fan and heavy... Read more
Free Verbum Catholic Bible Study App For iOS
The Verbum mobile app runs on Logos’ powerful Bible software and is an advanced resource for mobile Catholic study. The Verbum app surrounds the Bible with the Tradition. Verbum comes with 15 free... Read more
27-inch Apple iMacs on sale for up to $200 of...
B&H Photo has 27″ Apple iMacs on sale for up to $200 off MSRP, each including free shipping plus NY sales tax only: - 27″ 3.3GHz iMac 5K: $2099.99 $200 off MSRP - 27″ 3.2GHz/1TB Fusion iMac 5K: $... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for...
Amazon has 2015 15″ 2.2GHz Retina MacBook Pros (MJLQ2LL/A) available for $1849.99 including free shipping. Apple charges $1999 for this model, so Amazon’s price is represents a $150 savings. Read more
Apple refurbished iPad Air 2s available start...
Apple has Certified Refurbished iPad Air 2 WiFis available for starting at $319 including free shipping. A standard Apple one-year warranty is included: - 16GB iPad Air 2 WiFi: $319 $60 off original... Read more

Jobs Board

*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Manager *Apple* Systems Administration - Pu...
Req ID 3315BR Position Title Manager, Apple Systems Administration Job Description The Manager of Apple Systems Administration oversees the administration and Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Manager *Apple* Systems Administration - Pu...
Req ID 3315BR Position Title Manager, Apple Systems Administration Job Description The Manager of Apple Systems Administration oversees the administration and Read more
*Apple* Technician - nfrastructure (United S...
Let’s Work Together Apple Technician This position is based in Portland, ME Life at nfrastructure At nfrastructure, we understand that our success results from our Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.