我的代码是用来模拟篮球比赛的,它模拟一场30秒落后3分的比赛。
球员必须选择是投三分球,这需要更多的时间打成平局并重新获得控球权,还是快速投两分,速度更快,剩下的时间通过犯规(对手罚两个罚球,我们重新获得控球权)来重新获得控球权,而对方不能罚罚球。这场比赛被模拟了大约10000次,看看哪一场比赛的获胜率最高。问题是我的“have-goverage”是真/假(布尔值),但当我在函数中运行它时,它会作为int返回。此外,“pointsdifference”在每次运行代码时总是相同的
首先,为什么我的布尔变量作为整数返回? 其次,获胜率应该有所不同,因为这是一个随机实验,但只有两个结果。如何调整此代码以使我的模拟产生随机结果
import numpy as np
trials=10000
threeptpercentage=34.6
midrangepercentage=49.5
opposingmidrangepercentage=55.4
opponentfreethrowpercentage=60.6
timetoshoot2=4
timetoshoot3=7
timetofoul=2
offensereboundpercent=66.4
ftreboundpercent=64.3
pointsdown=3
timeleft=30
haveposession=True
wins3=0
wins2=0
wintake3=[]
wintake2=[]
def foul(timeleft,pointsdown,haveposession):
#if we don't have the posession, foul to regain posession
timeleft=timeleft-timetofoul
#opponent takes 2 free throw
if np.random.randint(1,101)<=opponentfreethrowpercentage:
pointsdown=pointsdown+1
if np.random.randint(1,101)<=opponentfreethrowpercentage:
pointsdown=pointsdown+1
haveposession=True
#opponent misses the freethrow and we rebound it
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=True
elif np.random.randint(1,101)<=offensereboundpercent:
pointsdown=pointsdown+2
haveposession=True
return haveposession,timeleft,pointsdown
def take3(timeleft,pointsdown,haveposession):
timeleft = timeleft-timetoshoot3
#do we make the shot?
if np.random.randint(1,101)<=threeptpercentage:
pointsdown=pointsdown-3
haveposession=False
#can we rebound?
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=False
pointsdown=pointsdown-2
elif np.random.randint(1,101)<=opposingmidrangepercentage:
pointsdown=pointsdown+2
haveposession=True
return haveposession,timeleft,pointsdown
#attempt to make a 2 and hope for another posession
def take2(timeleft,pointsdown,haveposession):
#if we are down by 3 or more, take the 2 quickly. if we are down by 2 or less, we tun down the clock
timeleft = timeleft-timetoshoot2
#do we make the shot?
if np.random.randint(1,101)<=midrangepercentage:
pointsdown=pointsdown-2
haveposession=False
#can the opponent rebound?
else:
if np.random.randint(1,101)<=ftreboundpercent:
haveposession=False
pointsdown=pointsdown-2
return haveposession,timeleft,pointsdown
for i in range(1,trials+1):
while timeleft>0:
if haveposession==True:
timeleft,pointsdown,haveposession=take3(timeleft,pointsdown,haveposession)
else:
timeleft,pointsdown,haveposession=foul(timeleft,pointsdown,haveposession)
if pointsdown<0:
wintake3.append(wins3)
while timeleft>0:
if haveposession==True:
timeleft,pointsdown,haveposession=take2(timeleft,pointsdown,haveposession)
else:
timeleft,pointsdown,haveposession=foul(timeleft,pointsdown,haveposession)
if pointsdown<0:
wintake2.append(wins2)
winrate3=len(wintake3)*100/trials
winrate2=len(wintake2)*100/trials
print('Winrate if shoot a 3-pointer =',winrate3,'%')
print('Winrate if shoot a 2-pointer =',winrate2,'%')
目前没有回答
相关问题 更多 >
编程相关推荐