실수 구현하기
깔끔하게 작성된 코드 덕분에, 랜덤 워크 시뮬레이션 횟수를 아주 쉽게 바꿀 수 있습니다. 가장 바깥쪽 for 반복문의 range() 함수만 수정하면 됩니다.
한 가지를 빠뜨렸네요! 여러분은 약간 덜렁거리는 편이라, 넘어질 확률이 0.5%입니다. 이 확률을 위한 난수를 하나 더 생성해야 합니다. 실수 0과 1 사이에 있는 실수 난수를 생성한 뒤, 그 값이 0.005 이하이면 step을 0으로 초기화하세요.
이 연습은 강의의 일부입니다
중급 Python
연습 안내
range()함수를 수정해 시뮬레이션을 20회 수행하도록 변경하세요.- 실수 난수가 0.005 이하일 때
if가 0으로 설정되도록step조건을 완성하세요.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()