python应用-随机漫步

Posted pprp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python应用-随机漫步相关的知识,希望对你有一定的参考价值。

对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应用-随机漫步的主要内容,如果未能解决你的问题,请参考以下文章

Python随机漫步

Python中的 matplotlib随机漫步

python 实现随机漫步

python Python - 随机漫步

python数据可视化--matplotlib进行随机漫步

python 随机漫步