Tcl Library Source Code

EuroTcl/OpenACS 11 - 12 JULY 2024, VIENNA

[ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]


simulation::montecarlo - Monte Carlo simulations

Table Of Contents


package require Tcl ?8.5 9?
package require simulation::montecarlo 0.2
package require simulation::random
package require math::statistics

::simulation::montecarlo::getOption keyword
::simulation::montecarlo::hasOption keyword
::simulation::montecarlo::setOption keyword value
::simulation::montecarlo::setTrialResult values
::simulation::montecarlo::setExpResult values
::simulation::montecarlo::transposeData values
::simulation::montecarlo::integral2D ...
::simulation::montecarlo::singleExperiment args


The technique of Monte Carlo simulations is basically simple:

You can think of a model of a network of computers, an ecosystem of some kind or in fact anything that can be quantitatively described and has some stochastic element in it.

The package simulation::montecarlo offers a basic framework for such a modelling technique:

# MC experiments:
# Determine the mean and median of a set of points and compare them
::simulation::montecarlo::singleExperiment -init {
    package require math::statistics

    set prng [::simulation::random::prng_Normal 0.0 1.0]
} -loop {
    set numbers {}
    for { set i 0 } { $i < [getOption samples] } { incr i } {
        lappend numbers [$prng]
    set mean   [::math::statistics::mean $numbers]
    set median [::math::statistics::median $numbers] ;# ? Exists?
    setTrialResult [list $mean $median]
} -final {
    set result [getTrialResults]
    set means   {}
    set medians {}
    foreach r $result {
        foreach {m M} $r break
        lappend means   $m
        lappend medians $M
    puts [getOption reportfile] "Correlation: [::math::statistics::corr $means $medians]"

} -trials 100 -samples 10 -verbose 1 -columns {Mean Median}

This example attemps to find out how well the median value and the mean value of a random set of numbers correlate. Sometimes a median value is a more robust characteristic than a mean value - especially if you have a statistical distribution with "fat" tails.


The package defines the following auxiliary procedures:

There are two main procedures: integral2D and singleExperiment.

The singleExperiment command predefines the following options:

Any other options can be used via the getOption procedure in the body.


The procedure singleExperiment works by constructing a temporary procedure that does the actual work. It loops for the given number of trials.

As it constructs a temporary procedure, local variables defined at the start continue to exist in the loop.


math, montecarlo simulation, stochastic modelling




Copyright © 2008 Arjen Markus