|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
她顯示 if temp[0] == 1:
IndexError: list index out of range
蒙地卡羅模擬
假設小名站在原點(0, 0),他可以選擇前進、後退、右轉、左轉,機率均為1/4。
計算走了50步,和原點的原點距離是多少?利用迴圈模擬30次,觀察這30次都落在什麼範圍。
import random
import math
site = [0, 0]
temp = [random.randrange(1, 5) for i in range(50)]
n = 0
list1 = []
list1.append(temp)
print(temp)
while len(temp) >= 0:
if temp[0] == 1:
site[0] += 1
elif temp[0] == 2:
site[0] -= 1
elif temp[0] == 3:
site[1] += 1
else:
site[1] -= 1
n += 1
del temp[0]
print(site)
distance = pow(site[0], 2) + pow(site[1], 2)
print(distance)
print(site)
应该是在不为空的情况下循环。 - import random
- import math
- site = [0, 0]
- temp = [random.randrange(1, 5) for i in range(50)]
- n = 0
- list1 = []
- list1.append(temp)
- print(temp)
- while temp:
- if temp[0] == 1:
- site[0] += 1
- elif temp[0] == 2:
- site[0] -= 1
- elif temp[0] == 3:
- site[1] += 1
- else:
- site[1] -= 1
- n += 1
- del temp[0]
- print(site)
- distance = pow(site[0], 2) + pow(site[1], 2)
- print(distance)
- print(site)
复制代码
|
|