Thursday, June 14, 2012

Random Number Generator (arcpy.env)

This is a tool that creates a random number based on a seed number and an algorithm selection.
Inputs are as follows:
  1. Seed—The seed is an integer value and is used to initiate the random number generator. The default value is 0.
  2. Random Generator Type—The random generator algorithm.


    • ACM599—ACM collected algorithm 599. This is the default.
    • MERSENNE_TWISTER—Mersenne Twister mt19937.
    • STANDARD_C—Standard C Rand

So to create a random number generation environmental variable you can do it two ways:

Option 1:

from arcpy import env
env.randomGenerator = "4 MERSENNE_TWISTER"


Option 2:

from arcpy import env
env.randomGenerator = arcpy.CreateRandomValueGenerator(4, "MERSENNE_TWISTER")



To produce a random number, the easiest way is to use the arcpy.CalculateValue() and get the results from that tool.
Example:

import arcpy
arcpy.env.randomGenerator = "4 MERSENNE_TWISTER"
result = arcpy.CalculateValue_management("arcgis.rand('normal 0.0 10.0')")
randomValue = float(result.getOutput(0))
print randomValue


The code should print a random number.

It should be noted that this environmental variable will effect any tool that uses random values.

Enjoy