week9

2018-08-08  本文已影响4人  猪蹄炖粥

chp14 随机游走与数据可视化

模拟模型:1、模仿实际系统的活动2、预测实验系统的未来状态

布朗运动是随机游走的一种

随机游走

import random
class Location(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
    
    def move(self,deltaX,deltaY):
        """
        deltaX,deltaY是数值型
        """
        return Location(self.x + deltaX , self.y+ deltaY)
    def getX(self):
        return self.x
    def getY(self):
        return self.y
    
    def distFrom(self,other):
        ox, oy = other.x ,other.y
        xDist, yDist = self.x - ox, self.y- oy
        return (xDist**2 + yDist**2)**0.5
    
    def __str__(self):
        return '<' + str(self.x) + ',' + str(self.y) + '>'

class Field(object):
    def __init__(self):
        self.drunks = {}
    
    def addDrunk(self,drunk,loc):
        if drunk in self.drunks:
            raise ValueError('Duplicate drunk')
        else:
            self.drunks[drunk] = loc
    
    def moveDrunk(self,drunk):
        if drunk not in self.drunks:   
            raise ValueError('Drunk not in field')
        xDist , yDist = drunk.takeStep()
        currentLocation = self.drunks[drunk]
        self.drunks[drunk] = currentLocation.move(xDist, yDist)
    def getLoc(self,drunk):
        if drunk not in self.drunks:
            raise ValueError('Drunk not in field')
        return self.drunks[drunk]

class Drunk(object):
    def __init__(self,name=None):
        """假设name是字符"""
        self.name = name
    def __str__(self):
        if self != None:
            return self.name    
        return 'Anonymous'
    
class UsualDrunk(Drunk):
    def takeStep(self):
        stepChoices = [(0,1),(0,-1),(1,0),(-1,0)]
        return random.choice(stepChoices)

def walk(f,d,numSteps):
    '''
        f:Field
        d:Drunk
        numSteps: step counts
    '''
    start = f.getLoc(d)
    for s in range(numSteps):
        f.moveDrunk(d)
    return start.distFrom(f.getLoc(d))

def simWalks(numSteps,numTrials,dClass):
    '''
    numSteps 
    '''
    Homer = dClass()
    origin = Location(0,0)
    distances = []
    for t in range(numTrials):
        f = Field()
        f.addDrunk(Homer,origin)
        distances.append(round(walk(f,Homer,numSteps),1))
    return distances

def drunkTest(walkLengths,numTrials,dClass):
    for numSteps in walkLengths:
        distances = simWalks(numSteps,numTrials,dClass)
        print(dClass.__name__,'random walk of',numSteps,'steps')
        print('Mean = ',round(sum(distances)/len(distances),4))
        print('Max = ',max(distances),'Min = ',min(distances))


drunkTest((10, 100, 1000, 10000), 100, UsualDrunk)

有机随机游走

即行为的倾向性

上一篇下一篇

猜你喜欢

热点阅读