问题遇到的现象和发生背景
昨天,我老公突然说,他高中的时候想到一个问题,一直没有得到解答,念头不通达。
问题是这样的:
一个箱子里有100个白球,每次随机抓一个后放回,抓到白球涂成红色,抓到红球直接放回;
这样抓100次之后,再抓到红球的期望是多少?
我当时觉得这个用编程算挺容易的,就写了下面的代码:
问题相关代码,请勿粘贴截图
rm(list = ls())
x = c(1)
r = c(1)
all_p = numeric()
for (i in 1:15) {
new_x = numeric()
new_r = numeric()
p = numeric()
for (j in 1:length(x)) {
y_1 = x[j]
y_2 = x[j] + 1
r_1 = r[j] * (x[j]/100)
r_2 = r[j] * ((100 - x[j])/100)
p_1 = r_1 * (y_1/100)
p_2 = r_2 * (y_2/100)
new_x = append(new_x, c(y_1, y_2))
new_r = append(new_r, c(r_1, r_2))
p = append(p, c(p_1, p_2))
}
x = new_x
r = new_r
p = sum(p)
print(paste0("After ",(i + 1) , ' Times, E for red ball is ', round(p * 100, 2)))
all_p = append(all_p, p)
}
plot(x = 1:length(all_p) + 1,
y = all_p * 100,
type = 'b',
xlab = 'Times',
ylab = 'E for Red Ball')
运行结果及报错内容
虽然开始运行很顺畅,但越到后面算量越大。我的笔记本吃不下了。
我的解答思路和尝试过的方法
下面是我的测试:
[1] "After 2 Times, E for red ball is 1.99"
[1] "After 3 Times, E for red ball is 2.97"
[1] "After 4 Times, E for red ball is 3.94"
[1] "After 5 Times, E for red ball is 4.9"
[1] "After 6 Times, E for red ball is 5.85"
[1] "After 7 Times, E for red ball is 6.79"
[1] "After 8 Times, E for red ball is 7.73"
[1] "After 9 Times, E for red ball is 8.65"
[1] "After 10 Times, E for red ball is 9.56"
[1] "After 11 Times, E for red ball is 10.47"
[1] "After 12 Times, E for red ball is 11.36"
[1] "After 13 Times, E for red ball is 12.25"
[1] "After 14 Times, E for red ball is 13.13"
[1] "After 15 Times, E for red ball is 13.99"
[1] "After 16 Times, E for red ball is 14.85"
我想要达到的结果
求个道友把程序跑一下;
或者,除了这种直球的解法,还有没有什么好的方法?这答案不算出来,念头不通达,谢谢各位了!