Here is an example of an R program that generates a random number from the standard normal distribution (also known as a Gaussian or normal distribution) using the rnorm()
function from the stats
library:
1 2 3 4 5 6 7 | # Generate a random number from the standard normal distribution x <- rnorm(n = 1) # Print the result print(paste("Random number:", x)) |
This program uses the rnorm()
function to generate a single random number from the standard normal distribution with a mean of 0 and a standard deviation of 1. The n
argument specifies the number of random numbers to generate, which in this case is 1. The result is stored in the variable x
You can generate random numbers from other distributions, like uniform, exponential and etc. For example, the runif()
function to generate random numbers from a uniform distribution with a specified range, the rexp()
function to generate random numbers from an exponential distribution.
Here’s an example for the uniform distribution:
1 2 3 4 5 6 7 | # Generate a random number from the uniform distribution x <- runif(n = 1, min = 0, max = 10) # Print the result print(paste("Random number:", x)) |
And an example for the exponential distribution
1 2 3 4 5 6 7 | # Generate a random number from the exponential distribution x <- rexp(n = 1, rate = 1) # Print the result print(paste("Random number:", x)) |
In R, the rnorm()
function generates random numbers from a normal distribution with a specified mean and standard deviation. By default, rnorm()
generates random numbers from the standard normal distribution, which has a mean of 0 and a standard deviation of 1.
The runif()
function generates random numbers from a uniform distribution, it take 3 arguments n
, min
, and max
where n
is the number of random numbers you want to generate, min
and max
specifies the range of the uniform distribution.
The rexp()
function generates random numbers from an exponential distribution, it takes 2 arguments n
and rate
where n
is the number of random numbers you want to generate and rate
is the inverse of the mean of the distribution.
The rnorm()
, runif()
and rexp()
are all part of the R base package and are used to generate random numbers from specific probability distributions. These functions are often used in simulations and statistical modeling. When you call these functions, R uses a built-in random number generator to produce a sequence of random numbers that follow the specified probability distribution.
You can also specify a seed for the random number generator using the set.seed()
function which allows you to reproduce the same sequence of random numbers for a given seed value. This can be useful for debugging and for comparing results between different runs of a simulation or statistical model.