python实现随机漫步算法

yipeiwu_com5年前Python基础

本文实例为大家分享了python实现随机漫步的具体代码,供大家参考,具体内容如下

编写randomwalk类

from random import choice

class randomwalk():

  def __init__(self,num_points=5000):

    self.num_points=num_points


    self.x_values=[0]
    self.y_values=[0]

  def fill_walk(self):


    while len(self.x_values)<self.num_points:
      x_direction=choice([1,-1])
      x_distance=choice([0,1,2,3,4,5])
      x_step=x_direction*x_distance
      y_direction=choice([1,-1])
      y_distance=choice([0,1,2,3,4,5])
      y_step=y_direction*y_distance

      if x_step==0 and y_step==0:
        continue

      self.x_values.append(self.x_values[-1]+x_step)
      self.y_values.append(self.y_values[-1]+y_step)

choice([1,-1])*步数巧妙的完成了随机方向,x轴随机加y轴随机使得4个方向的随机漫步得以完成

显示随机漫步点

import matplotlib.pyplot as plt
from random_walk import randomwalk


while True:
  rw=randomwalk()
  rw.fill_walk()
  plt.figure(figsize=(15,8))
  point_numbers=list(range(rw.num_points))

  plt.scatter(rw.x_values,rw.y_values,s=1,c=point_numbers,
  edgecolor='none',cmap=plt.cm.Blues)

  plt.scatter(rw.x_values[0],rw.y_values[0],s=50,edgecolor='none',
  c='green')

  plt.scatter(rw.x_values[-1],rw.y_values[-1],s=50,edgecolor='none',
  c='green')

  plt.show()

  a=input("do you want to walk again?(y/n)")
  if a=='n':
    break

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈django model的get和filter方法的区别(必看篇)

django的get和filter方法是django model常用到的,搞清楚两者的区别非常重要。 为了说明它们两者的区别定义2个models class Student(mode...

深入浅出分析Python装饰器用法

本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下: 用类作为装饰器 示例一 最初代码: class bol(object): def __init__(self...

Python中一些不为人知的基础技巧总结

前言 本文主要给大家总结介绍了关于Python的一些基础技巧,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 1.startswith()和endswith()参数可以...

python解析文件示例

python最近的工作主要是组件兼容性测试,原有的框架有很多功能还不完善,需要补充!比如,需要将AutoIt脚本的执行结果写入到Excel中,最后的解决方案是使用本地的log来解析这个结...

Python实现K折交叉验证法的方法步骤

学习器在测试集上的误差我们通常称作“泛化误差”。要想得到“泛化误差”首先得将数据集划分为训练集和测试集。那么怎么划分呢?常用的方法有两种,k折交叉验证法和自助法。介绍这两种方法的资料有很...