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

Yummy FTP Pro 1.11.14 - $14.99 (50% off)
Yummy FTP Pro is an advanced Mac file transfer app which provides a full-featured professional toolkit combined with blazing speeds and impeccable reliability, so whether you want to transfer a few... Read more
ExpanDrive 5.4.4 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Dash 3.4.3 - 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
Civilization VI 1.0.2 - Next iteration o...
Sid Meier’s Civilization VI is the next entry in the popular Civilization franchise. Originally created by legendary game designer Sid Meier, Civilization is a strategy game in which you attempt to... Read more
TurboTax 2016 - Manage your 2016 U.S. ta...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more
Microsoft Office 2016 15.30 - 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
FotoMagico 5.3 - Powerful slideshow crea...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more
Acorn 5.6.1 - Bitmap image editor.
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
iMazing 2.1.8 - Complete iOS device mana...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
Logic Pro X 10.3 - Music creation and au...
Logic Pro X is the most advanced version of Logic ever. Sophisticated new tools for professional songwriting, editing, and mixing are built around a modern interface that's designed to get creative... Read more

Red's Kingdom (Games)
Red's Kingdom 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Mad King Mac has kidnapped your father and stolen your golden nut! Solve puzzles and battle goons as you explore and battle your... | Read more »
Turbo League Guide: How to tame the cont...
| Read more »
Fire Emblem: Heroes coming to Google Pla...
Nintendo gave us our first look at Fire Emblem: Heroes, the upcoming mobile Fire Emblem game the company hinted at last year. Revealed at the Fire Emblem Direct event held today, the game will condense the series' tactical RPG combat into bite-... | Read more »
ReSlice (Music)
ReSlice 1.0 Device: iOS Universal Category: Music Price: $9.99, Version: 1.0 (iTunes) Description: Audio Slice Machine Slice your audio samples with ReSlice and create flexible musical atoms which can be triggered by MIDI notes or... | Read more »
Stickman Surfer rides in with the tide t...
Stickson is back and this time he's taken up yet another extreme sport - surfing. Stickman Surfer is out this Thursday on both iOS and Android, so if you've been following the other Stickman adventures, you might be interested in picking this one... | Read more »
Z-Exemplar (Games)
Z-Exemplar 1.4 Device: iOS Universal Category: Games Price: $3.99, Version: 1.4 (iTunes) Description: | Read more »
5 dastardly difficult roguelikes like th...
Edmund McMillen's popular roguelike creation The Binding of Isaac: Rebirth has finally crawled onto mobile devices. It's a grotesque dual-stick shooter that tosses you into an endless, procedurally generated basement as you, the pitiable Isaac,... | Read more »
Last week on PocketGamer
Welcome to a weekly feature looking back on the past seven days of coverage on our sister website, PocketGamer. It’s taken a while for 2017 to really get going, at least when it comes to the world of portable gaming. Thank goodness, then, for... | Read more »
ROME: Total War - Barbarian Invasion set...
To the delight of mobile strategy fans, Feral Interactive released ROME: Total War just a few months ago. Now the game's expansion, Barbarian Invasion is marching onto iPads as a standalone release. [Read more] | Read more »
Yuri (Games)
Yuri 1.0 Device: iOS iPhone Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: It's night. Yuri opens his eyes. He wakes up in a strange forest.The small, courageous explorer rides on his bed on casters in this... | Read more »

Price Scanner via

13-inch 2.7GHz Retina MacBook Pro on sale for...
B&H Photo has the 2015 13″ 2.7GHz/128GB Retina Apple MacBook Pro on sale for $100 off MSRP. Shipping is free, and B&H charges NY tax only: - 13″ 2.7GHz/128GB Retina MacBook Pro (MF839LL/A): $... Read more
Laptop Market – Flight To Quality? – The ‘Boo...
Preliminary quarterly PC shipments data released by Gartner Inc. last week reveal an interesting disparity between sales performance of major name PC vendors as opposed to that of less well-known... Read more
IBM and Bell Transform Canadian Enterprise Mo...
IBM and Bell Canada have announced they are joining forces to offer IBM MobileFirst for iOS market-ready enterprise applications for iPad, iPhone or Apple Watch. Bell, Canada’s largest communications... Read more
Otter Products is Closing… For a Day of Givin...
On Thursday, Feb. 9, Otter Products is closing doors to open hearts. In partnership with the OtterCares Foundation, the company is pausing operations for a day so all employees can volunteer with... 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 $1799.99 including free shipping. Apple charges $1999 for this model, so Amazon’s price is represents a $200 savings. Read more
Back in stock: Apple refurbished 13-inch Reti...
Apple has Certified Refurbished 2015 13″ Retina MacBook Pros available for up to $360 off original MSRP, starting at $1099. An Apple one-year warranty is included with each model, and shipping is... Read more
CalcTape for macOS 1.2 Adding Machine App for...
schoettler Software has announced CalcTape 1.2, an update to their desktop calculator for macOS. When it comes to adding long columns of numbers, doing complex calculations or playing around with... Read more
New MacBooks And MacBook Pros WIth Kaby Lake...
Digitimes’ Joseph Tsai cites a Chinese-language Economic Daily News (EDN) report that unnamed market watchers are predicting Apple MacBook shipments to grow 10 percent in 2017, and projecting 15... Read more
New 2016 13-inch MacBook Pros on sale for up...
B&H Photo has the new 2016 13″ MacBook Pros in stock today and on sale for up to $150 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 2.9GHz/512GB Touch Bar MacBook Pro... Read more
New 15-inch Touch Bar MacBook Pros in stock a...
B&H Photo has the new 2016 15″ Apple Touch Bar MacBook Pros in stock today and on sale for up to $150 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.7GHz Touch Bar... Read more

Jobs Board

*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Los Angeles, CA Introduction: We have immediate job openings for several Desktop Support Technicians with one of our Read more
*Apple* Retail - Multiple Positions - Apple,...
SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (Multi-L...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, 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
*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Stamford, CT We have immediate job openings for several Desktop Support Technicians with one of our most well-known Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.