Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R runif() Function - Generating Uniform Random Numbers

R runif() Function - Generating Uniform Random Numbers

R Language Examples R Language Examples

The R runif() function is used to generate random numbers following a uniform distribution.

A uniform distribution means every value in a specified interval is equally likely. 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:

Example

Generate 10 uniform random numbers in the interval [0, 1]

set.seed

(

123

)

random_01

<-

runif

(

10

)

print

(

"Random numbers in [0, 1]:"

)

print

(

round

(

random_01,

4

)

)

Generate random numbers in the interval [10, 50]

set.seed

(

123

)

random_range

<-

runif

(

10

,

min

=

10

,

max

=

50

)

print

(

"Random numbers in [10, 50]:"

)

print

(

round

(

random_range,

2

)

)

The output of the code above is:

[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

Estimate the value of pi using the Monte Carlo method

set.seed

(

123

)

n

<-

10000

Generate random points

x

<-

runif

(

n

)

y

<-

runif

(

n

)

Compute the proportion 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

)

)

The output of the code above is:

[1] "估算的 pi 值: 3.156"

[1] "实际的 pi 值: 3.14159265358979"

R Language Examples R Language Examples