You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

简化R语言硬币翻转模拟:跟踪累计正反面次数

简化的R语言硬币模拟方案

核心思路

利用R的向量化特性替代逐枚循环操作,通过矩阵统一存储状态和累计数据,既简化代码结构,又提升运行效率。

代码实现

# 初始化参数
n_coins <- 100
n_rounds <- 100

# 第0轮初始化硬币状态:1代表正面,0代表反面
initial_state <- sample(c(1, 0), n_coins, replace = TRUE, prob = c(0.5, 0.5))

# 存储每轮结束后的硬币状态(行=轮次,列=硬币)
state_matrix <- matrix(NA, nrow = n_rounds, ncol = n_coins)
state_matrix[1, ] <- initial_state

# 存储每轮每枚硬币的累计正面/反面次数
cum_positive <- matrix(NA, nrow = n_rounds, ncol = n_coins)
cum_negative <- matrix(NA, nrow = n_rounds, ncol = n_coins)
cum_positive[1, ] <- initial_state
cum_negative[1, ] <- 1 - initial_state

# 模拟后续轮次
for (round in 2:n_rounds) {
  prev_state <- state_matrix[round - 1, ]
  
  # 生成每枚硬币是否被选中翻转(1=选中,0=未选中)
  selected <- sample(c(1, 0), n_coins, replace = TRUE, prob = c(0.5, 0.5))
  
  # 生成翻转结果:选中的硬币有0.6概率保持原状态,0.4概率翻面;未选中的直接保留原状态
  flip_retain <- sample(c(1, 0), n_coins, replace = TRUE, prob = c(0.6, 0.4))
  new_state <- ifelse(selected == 1, ifelse(flip_retain == 1, prev_state, 1 - prev_state), prev_state)
  
  # 更新状态与累计数据
  state_matrix[round, ] <- new_state
  cum_positive[round, ] <- cum_positive[round - 1, ] + new_state
  cum_negative[round, ] <- round - cum_positive[round, ]
}

# 示例:查看第7轮第43枚硬币的累计次数
cat("第7轮coin43累计正面次数:", cum_positive[7, 43], "\n")
cat("第7轮coin43累计反面次数:", cum_negative[7, 43], "\n")

关键简化点

  • 向量化处理:所有硬币的选中判断、状态更新均通过向量操作完成,避免逐枚循环
  • 累计值推导:反面累计次数直接用当前轮次减去正面累计次数,无需单独累加,减少冗余计算
  • 结构化存储:用矩阵统一管理状态和累计数据,便于后续查看与分析

示例验证

如果要复现题目中的coin43案例,可手动模拟状态序列验证逻辑:

# 模拟示例中的状态序列:1(正)、0(反)、0(反)、0(反)、1(正)、1(正)、0(反)
example_states <- c(1, 0, 0, 0, 1, 1, 0)
example_cum_pos <- cumsum(example_states)
example_cum_neg <- 1:7 - example_cum_pos

# 输出结果:正面3次,反面4次
cat("示例累计正面次数:", example_cum_pos[7], "\n")
cat("示例累计反面次数:", example_cum_neg[7], "\n")

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:02:32