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

R语言下以植物采样为例的概率计算与绘图问题求解

原代码问题排查
  • 循环内每次执行plantNum <- c()清空存储向量,累计和永远只能等于单小时采样的水葫芦数(单小时期望仅10株),永远达不到100的阈值,导致死循环
  • 初始变量定义逻辑错误:hour初始为空向量无法直接做加法运算,定义的hours <- 9:00没有实际参与运算
  • 需求是计算有95%概率采够100株的时间,原代码是单次随机模拟刚好采到100株的时间,逻辑完全不匹配
实现思路

每采样t小时,总采样植物量为500*t株,水葫芦数量服从二项分布Bin(n=500*t, p=0.02),我们需要找到最小的t,使得P(水葫芦数量≥100) ≥ 0.95,同时存储每小时对应的概率绘制折线图。

可运行代码
library(tidyverse)

# 初始化变量
t <- 0 # 采样时长(小时)
prob_df <- data.frame(hour = integer(), prob = numeric()) # 存储时间和对应概率
target_prob <- 0.95
current_prob <- 0

# 循环计算直到概率达标
while(current_prob < target_prob){
  t <- t + 1
  total_plant <- 500 * t
  # 计算采到至少100株水葫芦的概率:1 - 累积概率到99株
  current_prob <- 1 - pbinom(q = 99, size = total_plant, prob = 0.02)
  # 存储结果:实际时间为9点加t小时
  prob_df <- rbind(prob_df, data.frame(hour = 9 + t, prob = current_prob))
}

# 输出结果
cat("可以结束采样的时间为:", prob_df$hour[nrow(prob_df)], "点,对应概率为", round(current_prob,4), "\n")

# 绘制时间与概率的折线图
ggplot(prob_df, aes(x = hour, y = prob)) +
  geom_line(color = "steelblue", linewidth = 1) +
  geom_point(color = "red", size = 2) +
  geom_hline(yintercept = 0.95, linetype = "dashed", color = "gray50") +
  labs(x = "时间(24小时制)", y = "采到至少100株水葫芦的概率", title = "采样时长与达标概率关系") +
  scale_y_continuous(labels = scales::percent) +
  theme_minimal()
输出说明

运行代码后会直接输出符合要求的结束采样时间,同时生成对应的折线图,图中灰色虚线为95%概率阈值,红色点为每小时对应的达标概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:15:04