首页 > 编程语言 > 详细

python应用-随机漫步

时间:2018-09-29 12:51:26      阅读:194      评论:0      收藏:0      [点我收藏+]

对python应用的一个巩固,以及熟悉matplotlib的用法

效果如下:
技术分享图片

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 22:39:55 2018
@author: pprp
"""

from random import choice
import matplotlib.pyplot as plt

class RandomWalk():
    """a class using to generate random data"""
    def __init__(self,num_points=5000):
        """init the class"""
        self.num_points=num_points
        
        # start at (0,0)
        self.x_val=[0]
        self.y_val=[0]
        
    def fill_walk(self):
        """calculate the points"""
        while len(self.x_val) < 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([1,2,5,4,0])
            y_step = y_direction * y_distance
            
            if x_step == 0 and y_step == 0:
                continue
            next_x = self.x_val[-1]+x_step
            next_y = self.y_val[-1]+y_step
            
            self.x_val.append(next_x)
            self.y_val.append(next_y)
            
rw = RandomWalk(50000)
rw.fill_walk()

plt.tick_params(axis='both',labelsize=14)

point_nums=list(range(rw.num_points))
plt.scatter(rw.x_val,rw.y_val,s=1,c=point_nums,cmap=plt.cm.Blues,edgecolors='none')

# plot the start point and end point
plt.scatter(0,0,c='green',edgecolors='none',s=100)
plt.scatter(rw.x_val[-1],rw.y_val[-1],c='red',edgecolors='none',s=100)

# set figure width and height
plt.figure(dpi=1280,figsize=(10,6))
plt.show()

python应用-随机漫步

原文:https://www.cnblogs.com/pprp/p/9723030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!