这是今天的一个错误(昨天用还没有报错),是想试试《python编程——从入门到实践》这本书里面的随机漫步,代码和错误都在这里,帮我看看行吗?
26行代码绘制散点图的时候有点bug哦
plt.scatter(rw.x, rw.y, c='r', s=20)
效果图如下:
可以绘制个更好看的样式哦
from random import choice
import matplotlib.pyplot as plt
class Randomwalk():
def __init__(self, num=1000):
self.x = [0]
self.y = [0]
self.num = num
def walk(self):
while len(self.x) < self.num:
x_direction = choice([-1, 1])
x_distance = choice([0, 1, 2, 3, 4, 5])
x_move = x_direction * x_distance
y_direction = choice([-1, 1])
y_distance = choice([0, 1, 2, 3, 4, 5])
y_move = y_direction * y_distance
if x_move == 0 and y_move == 0:
continue
next_x = self.x[-1] + x_move
next_y = self.y[-1] + y_move
self.x.append(next_x)
self.y.append(next_y)
rw = Randomwalk(num=1000)
rw.walk()
plt.figure(figsize=(10, 6))
# 点的大小s:80,颜色r: 红色,点样式*:五角星
plt.scatter(rw.x, rw.y, c='r', marker='*', s=80)
plt.show()
如有帮助请采纳哦~