#native_company# #native_desc#
#native_cta#

Weighted Random Number Generator

By Josh
on September 4, 2008

Version: 1.0

Type: Function

Category: Algorithms

License: Other

Description: This is a function that randomly generates an integer between two specified integers (which may include them). It works just like rand() except it has a factor parameter which specifies how exponential the probability differences between numbers can be. Passing a value of 1, in this case would give all numbers in the range an equal chance of being selected. A value of 2 should be sufficient in most cases, but it you want high numbers to occur less frequently, use higher values.

This function can be used for getting random indexes from an array, where the lower the index, the higher the chances of it being selected. It can also be used for randomly pulling lines from a flatfile, where the first line is most likely to be chosen, and where the last line is least likely to be chosen.

This function wasn’t tested with negative or floating-point values, so be warned.

You may use this freely or modify it at your own will. I’m just glad to share the solution to a problem I spent all day on. 🙂

function wrand($min, $max, $factor) {
  
  return round($min + (pow(rand(0, $max) / $max, $factor) * ($max - $min)));

}