Skip to content

Instantly share code, notes, and snippets.

@leontabak
Created September 29, 2021 15:02
Show Gist options
  • Save leontabak/13606cbea429ccd4fec2b5a0ea54b0d9 to your computer and use it in GitHub Desktop.
Save leontabak/13606cbea429ccd4fec2b5a0ea54b0d9 to your computer and use it in GitHub Desktop.
fill a list with numbers drawn from an exponential distribution
import kotlin.math.ln
fun main() {
// a specified mean for an exponential
// distribution of random numbers
val specifiedMean = 3.0
// create a random number generator
val rng = kotlin.random.Random(System.nanoTime())
// define a function that creates a function
// * rng.nextDouble() returns a random number
// in [0.0, 1.0) with equal probability of
// drawing any number in the range
// (it draws from a uniform distribution)
// * -mean * ln(rng.nextDouble()) returns a
// random number drawn from an exponential
// distribution with the specified mean
// (the number will be non-negative, has
// no upper bound, and is more likely to
// be small than large)
//
// * makeExpRNG is a function with one floating
// point parameter
// * makeExpRNG returns a function that has one
// integer parameter
// * the function that makeExpRNG returns in turn
// returns a random number drawn from an
// exponential distribution
// * the right-hand side of this assignment is
// a lambda that returns a lambda1
val makeExpRNG =
{ mean:Double -> { n:Int -> -mean * ln(rng.nextDouble()) }}
// create the random number generator function
// to use in filling a list with random numbers
//
// expRng is a function with one integer parameter
// that returns a floating point value to its caller
//
// it is not necessary to include the type of
// expRNG explicitly---the Kotlin compiler can
// infer the type---I have included it here to
// help the reader see more clearly what is
// happening
val expRNG: (Int) -> Double = makeExpRNG( specifiedMean )
// create a list of 1024 random numbers,
// each drawn from an exponential distribution
// with a specified mean
//
// * expRNG is a function whose one parameter
// is an integer.
// * that integer will be the index of an
// element of the list
// * in this case, the function does nothing
// with the index
// * for each index, the function returns
// a random number drawn from an exponential
// distribution with a specified mean
val data = List<Double>(1024, expRNG )
// * we expect that that smallest number
// in the list will be very close to zero
// * we expect that the largest number
// in the list will be larger than the
// specified mean
// * we expect that the mean to be very
// nearly equal to the specified mean
val min = data.minOrNull()
val max = data.maxOrNull()
val mean = data.average()
println("minimum = $min")
println("maximum = $max")
println("mean = $mean")
} // main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment