R runif() function - Generate uniformly distributed random numbers
The R runif() function is used to generate random numbers that follow a uniform distribution.
A uniform distribution means that every value within a specified interval has an equal probability of occurring. It is often used as a basic distribution in random sampling and simulation experiments.
The syntax of the runif() function is as follows:
runif(n, min = 0, max = 1)
Parameter description:
nThe number of random numbers to generate.
minMinimum value, default is 0.
maxMaximum value, default is 1.
Example
# Generate 10 uniformly distributed random numbers in the interval [0, 1]
set.seed(123)
random_01 <- runif(10)
print("Random numbers in the [0, 1] interval:")
print(round(random_01, 4))
# Generate random numbers in the [10, 50] interval
set.seed(123)
random_range <- runif(10, min = 10, max = 50)
print("Random numbers in the [10, 50] interval:")
print(round(random_range, 2))
set.seed(123)
random_01 <- runif(10)
print("Random numbers in the [0, 1] interval:")
print(round(random_01, 4))
# Generate random numbers in the [10, 50] interval
set.seed(123)
random_range <- runif(10, min = 10, max = 50)
print("Random numbers in the [10, 50] interval:")
print(round(random_range, 2))
Executing the above code produces the following result:
[1] "[0, 1] 区间随机数:" [1] 0.2876 0.7883 0.4090 0.8830 0.9405 0.0456 0.5281 [8] 0.8924 0.5519 0.4566 [1] "[10, 50] 区间随机数:" [1] 21.50 41.53 26.36 45.32 47.62 11.82 31.12 45.70 [9] 32.08 28.26
runif() is very useful in Monte Carlo simulations:
Example
# Use the Monte Carlo method to estimate the value of pi
set.seed(123)
n <- 10000
# Generate random points
x <- runif(n)
y <- runif(n)
# Calculate the proportion of points falling inside the unit circle
inside <- (x^2 + y^2) <= 1
pi_estimate <- 4 * mean(inside)
print(paste("Estimated pi value:", round(pi_estimate, 4)))
print(paste("Actual pi value:", pi))
set.seed(123)
n <- 10000
# Generate random points
x <- runif(n)
y <- runif(n)
# Calculate the proportion of points falling inside the unit circle
inside <- (x^2 + y^2) <= 1
pi_estimate <- 4 * mean(inside)
print(paste("Estimated pi value:", round(pi_estimate, 4)))
print(paste("Actual pi value:", pi))
Executing the above code produces the following result:
[1] "估算的 pi 值: 3.156" [1] "实际的 pi 值: 3.14159265358979"Other extensions
R language examples