YouTip LogoYouTip

R Func Runif

# R runif() Function - Generating Uniform Distribution Random Numbers [![Image 3: R Language Examples](#) R Language Examples](#) The R runif() function is used to generate random numbers that follow a uniform distribution. Uniform distribution means that each value within a specified interval has an equal probability of appearing. It is often used as a base distribution in random sampling and simulation experiments. The runif() function syntax format is as follows: runif(n, min = 0, max = 1) **Parameter Description:** * **n** The number of random numbers to generate. * **min** The minimum value, default is 0. * **max** The maximum value, default is 1. ## Examples # Generate 10 uniform distribution random numbers in [0, 1] interval set.seed(123) random_01 <-runif(10) print("[0, 1] interval random numbers:") print(round(random_01, 4)) # Generate random numbers in [10, 50] interval set.seed(123) random_range <-runif(10, min=10, max=50) print("[10, 50] interval random numbers:") print(round(random_range, 2)) The output result of executing the above code is: "[0, 1] interval random numbers:" 0.2876 0.7883 0.4090 0.8830 0.9405 0.0456 0.5281 0.8924 0.5519 0.4566 "[10, 50] interval random numbers:" 21.50 41.53 26.36 45.32 47.62 11.82 31.12 45.70 32.08 28.26 runif() is very useful in Monte Carlo simulations: ## Examples # Estimate pi value using Monte Carlo method set.seed(123) n <-10000 # Generate random points x <-runif(n) y <-runif(n) # Calculate the proportion falling within 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)) The output result of executing the above code is: "Estimated pi value: 3.156" "Actual pi value: 3.14159265358979" [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func SapplyR Func Round β†’