📜  在 R 编程中创建均匀分布的随机偏差 – runif()函数

📅  最后修改于: 2022-05-13 01:54:50.064000             🧑  作者: Mango

在 R 编程中创建均匀分布的随机偏差 – runif()函数

R 语言中的runif()函数用于创建均匀分布的随机偏差。

示例 1:

r
# Create uniform distribution between range -1 to 1
x <- runif(20, min = -1, max = 1)
 
# Print distribution
print(x)


r
# Create uniform distribution of range -5 to 5
unif <- runif(10000, min = -5, max = 5)
 
# Output to be present as PNG file
png(file = "runifGFG.png")
 
# Create Histogram
hist(unif, freq = FALSE,
     xlab = 'x', 
     ylim = c(0, 0.4),
     xlim = c(-6, 6),
     density = 20,
     main = "Uniform distribution for the interval [-5, 5]")
 
# Show density of distribution using curve
curve(dunif(x, min = -5, max = 5),
      from = -10, to = 10,
      n = 100000,
      col = "darkgreen",
      lwd = 2,
      add = TRUE,
      yaxt = "n",
      ylab = 'probability')
 
# Saving the file
dev.off()


输出:

[1]  0.90453974 -0.97083088  0.83531295  0.19008941  0.52278078 -0.75730955
 [7]  0.21659920 -0.26621211  0.11967620  0.42081991  0.75518470 -0.41519833
[13] -0.03734007  0.57365077  0.76156708  0.97314141 -0.41957919 -0.08910355
[19]  0.29047038 -0.67069856

示例 2:

r

# Create uniform distribution of range -5 to 5
unif <- runif(10000, min = -5, max = 5)
 
# Output to be present as PNG file
png(file = "runifGFG.png")
 
# Create Histogram
hist(unif, freq = FALSE,
     xlab = 'x', 
     ylim = c(0, 0.4),
     xlim = c(-6, 6),
     density = 20,
     main = "Uniform distribution for the interval [-5, 5]")
 
# Show density of distribution using curve
curve(dunif(x, min = -5, max = 5),
      from = -10, to = 10,
      n = 100000,
      col = "darkgreen",
      lwd = 2,
      add = TRUE,
      yaxt = "n",
      ylab = 'probability')
 
# Saving the file
dev.off()

输出: