開始使用免費開始

實作「手殘」情境

因為你把程式碼寫得很俐落,所以要改變隨機漫步要模擬的次數非常容易。你只要更新最外層 for 迴圈中的 range() 函式即可。

不過還有件事我們忘了!你有點手殘,跌倒的機率是 0.5%。這需要再做一次隨機數產生。基本上,你可以產生介於 01 的隨機浮點數。若這個值小於或等於 0.005,就把 step 重設為 0。

本練習屬於課程

Python 中級

檢視課程

練習說明

  • range() 函式改成讓模擬執行 20 次。
  • 完成 if 條件:當隨機浮點數小於或等於 0.005 時,把 step 設為 0。使用 np.random.rand()

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# numpy and matplotlib imported, seed set

# clear the plot so it doesn't get cluttered if you run this many times
plt.clf()

# Simulate random walk 20 times
all_walks = []
for i in range(5) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)

        # Implement clumsiness
        if ___ :
            step = 0

        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()
編輯並執行程式碼