packages feed

zeolite-lang-0.18.1.0: lib/math/random.0rt

/* -----------------------------------------------------------------------------
Copyright 2021 Kevin P. Barry

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------- */

// Author: Kevin P. Barry [ta0kira@gmail.com]

testcase "valid instantiations" {
  success
}

unittest exponential {
  Generator<Float> random <- RandomExponential.new(1.0)
  Float value <- random.generate()
}

unittest gaussian {
  Generator<Float> random <- RandomGaussian.new(0.0,1.0)
  Float value <- random.generate()
}

unittest uniform {
  Generator<Float> random <- RandomUniform.new(0.0,1.0)
  Float value <- random.generate()
}


testcase "negative lambda in exponential" {
  crash
  require "lambda"
  require "-1"
}

unittest test {
  Generator<Float> random <- RandomExponential.new(-1.0)
}


testcase "negative standard deviation in gaussian" {
  crash
  require "standard deviation"
  require "-1"
}

unittest test {
  Generator<Float> random <- RandomGaussian.new(0.0,-1.0)
}


testcase "empty range in uniform" {
  crash
  require "range"
  require "0,-1"
}

unittest test {
  Generator<Float> random <- RandomUniform.new(0.0,-1.0)
}


testcase "distribution sanity checks" {
  success
}

unittest exponential {
  Int count <- 10000
  Float lambda <- 10.0
  $ReadOnly[count,lambda]$

  Generator<Float> random <- RandomExponential.new(lambda)

  Float sum <- 0.0
  traverse (Counter.zeroIndexed(count) -> _) {
    Float value <- random.generate()
    \ Testing.checkGreaterThan<?>(value,0.0)
    sum <- sum+value
  }

  \ Testing.checkBetween<?>(sum/count.asFloat(),0.9/lambda,1.1/lambda)
}

unittest gaussian {
  Int count <- 10000
  Float mean <- 100.0
  Float sd <- 1.0
  $ReadOnly[count,mean,sd]$

  Generator<Float> random <- RandomGaussian.new(mean,sd)

  Float sum <- 0.0
  traverse (Counter.zeroIndexed(count) -> _) {
    sum <- sum+random.generate()
  }

  \ Testing.checkBetween<?>(sum/count.asFloat(),mean-0.1*sd,mean+0.1*sd)
}

unittest uniform {
  Int count <- 10000
  Float min <- -11.0
  Float max <- 5.0
  $ReadOnly[count,min,max]$

  Generator<Float> random <- RandomUniform.new(min,max)

  Float sum <- 0.0
  traverse (Counter.zeroIndexed(count) -> _) {
    Float value <- random.generate()
    \ Testing.checkBetween<?>(value,min,max)
    sum <- sum+value
  }

  \ Testing.checkBetween<?>(sum/count.asFloat(),min-0.1*(max-min),max-0.1*(max-min))
}