How to generate random values from a distribution (in Julia)
Task
There are many famous continuous probability distributions, such as the normal and exponential distributions. How can we get access to them in software, to generate random values from a chosen distribution?
Related tasks:
- How to compute probabilities from a distribution
- How to plot continuous probability distributions
- How to plot discrete probability distributions
Solution
You can import many different random variables from Julia’s Distributions
package.
The full list of them is online here.
If you don’t have that package installed, first run using Pkg
and then
Pkg.add( "Distributions" )
from within Julia.
Regardless of whether the distribution is discrete or continuous,
the appropriate function to call is rand
.
Here are two examples.
Using a normal distribution:
1
2
3
using Distributions
X = Normal( 5, 3 )
rand( X, 10 )
1
2
3
4
5
6
7
8
9
10
11
10-element Vector{Float64}:
2.18036354985213
4.261755639220276
9.175724974437623
7.111178500969482
5.784059237346303
2.276916458848387
4.323059921916803
7.067942300207913
5.040815993440384
5.401080085074974
Using a uniform distribution:
In this example, we generate the random values in one line of code, without giving the random variable a name.
1
2
using Distributions
rand( Uniform( 100, 200 ), 5 )
1
2
3
4
5
6
5-element Vector{Float64}:
120.34366617283129
117.18012200542422
121.03058480958376
140.31797801233535
109.153400454394
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)