You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在R语言中模拟随机游走?以及如何生成服从P(Xn=1)=1/2、P(Xn=-1)=1/2分布的随机变量序列用于随机游走模拟?

Got it, let's break down these two related tasks in R clearly—first generating the required symmetric random variable sequence, then using it to simulate a 1D random walk.

1. Generate the Symmetric Random Variable Sequence

We need a sequence where each element is either 1 or -1, each with a 50% probability. R's sample() function is perfect for this, since we can explicitly set the probabilities and sample with replacement (to get independent, identically distributed values).

# Set a seed for *reproducibility* (optional but highly recommended if you want consistent results)
set.seed(42)

# Define how many steps (elements) you want in the sequence
n_steps <- 1000

# Generate the sequence: 1 and -1, each with 0.5 probability, sampled with replacement
random_seq <- sample(x = c(1, -1), size = n_steps, replace = TRUE, prob = c(0.5, 0.5))

# Quick check to verify the distribution (should be ~50% each)
table(random_seq) / length(random_seq)

Notes:

  • The set.seed() line ensures anyone running this code gets the exact same sequence—great for debugging or sharing results.
  • replace = TRUE is critical here because we want independent draws (each element doesn't affect the next).
2. Simulate the Random Walk

A 1D random walk is just the cumulative sum of our random sequence: each step adds the current value from random_seq to the previous position. We usually start at position 0 (step 0) before taking any steps.

# Calculate the walk path: start at 0, then add each step from the sequence
random_walk <- c(0, cumsum(random_seq))

# Visualize the walk with a plot
plot(
  x = 0:n_steps,  # X-axis: step number (0 to n_steps)
  y = random_walk,
  type = "l",  # Line plot for smooth path
  main = "*1D Symmetric Random Walk*",
  xlab = "Step Number",
  ylab = "Current Position",
  col = "darkblue",
  lwd = 1.5
)
# Add a dashed red line at position 0 (starting point) for reference
abline(h = 0, col = "red", lty = 2)

Bonus: Simulate Multiple Random Walks

If you want to compare multiple walks at once, use replicate() to generate several paths:

# Number of walks to simulate
n_walks <- 5

# Generate all walks at once
multiple_walks <- replicate(
  n = n_walks,
  expr = c(0, cumsum(sample(c(1, -1), n_steps, replace = TRUE, prob = c(0.5, 0.5))))
)

# Plot all walks
matplot(
  x = 0:n_steps,
  y = multiple_walks,
  type = "l",
  main = "*Multiple 1D Symmetric Random Walks*",
  xlab = "Step Number",
  ylab = "Position",
  col = 1:n_walks,
  lty = 1,
  lwd = 1.2
)
abline(h = 0, col = "red", lty = 2)
# Add a legend to distinguish walks
legend("topright", legend = paste("Walk", 1:n_walks), col = 1:n_walks, lty = 1)

内容的提问来源于stack exchange,提问作者fran

火山引擎 最新活动