当前位置: 首页>>代码示例>>Python>>正文


Python random.random函数代码示例

本文整理汇总了Python中random.random.random函数的典型用法代码示例。如果您正苦于以下问题:Python random函数的具体用法?Python random怎么用?Python random使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了random函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update

    def update(self):
        #

        if self.stateMachine != None:
            if self.hitWall == True:
                self.stateMachine.nextState((0,1,0)) 
            else:  
                self.stateMachine.nextState((0,0,0))        
            currentState = self.stateMachine.getCurrentState()
    
            if isinstance(currentState, StateMoveCurrentDirection):
                self.moveX = 0
                self.moveY = 0 
                if self.direction == LEFT:
                    self.next_frame()
                    self.isMoving = True
                    self.movement = (WALK_SPEED, 0, LEFT)
                    if random.random() > 0.9:
                        self.is_firing = True
                    else:
                        self.is_firing = False                     
                elif self.direction == RIGHT:
                    self.next_frame()
                    self.isMoving = True
                    self.movement = (WALK_SPEED, 0, RIGHT)
                    if random.random() > 0.9:
                        self.is_firing = True
                    else:
                        self.is_firing = False                     
    
            elif isinstance(currentState, StateChangeDirection):
                self.hitWall = False
                self.isMoving = False
                self.set_reverse_direction()          
开发者ID:Solivagant,项目名称:Flashlight-JI,代码行数:34,代码来源:Enemy.py

示例2: get_rejection_sample_disk

def get_rejection_sample_disk() -> (float, float):
    sx = sy = 0.0
    while True:
        sx = 1.0 - 2.0 * random.random()
        sy = 1.0 - 2.0 * random.random()
        if sx * sx + sy * sy > 1.0:
            break
    return sx, sy
开发者ID:neodyme60,项目名称:raypy,代码行数:8,代码来源:tools.py

示例3: generate_pointwise_data

def generate_pointwise_data(length, indexExistsProb=0.5, valueMean=2, fp=sys.stdout):
    """Generate random pointwise data.

    """

    import random
    for index in xrange(int(length/indexExistsProb)):
        if random.random() > indexExistsProb:
            fp.write("%i\t%f\n" % ( index, 2*valueMean*random.random() ))
开发者ID:maximilianh,项目名称:maxtools,代码行数:9,代码来源:encode.py

示例4: update_velocity

def update_velocity(particle, global_best, max_v, c1, c2, omega):
    import random
    for i in range(len(particle['velocity'])):
        v = particle['velocity'][i]
        v1 = c1 * random.random() * (particle['b_position'][i] - particle['position'][i])
        v2 = c2 * random.random() * (global_best['position'][i] - particle['position'][i])
        particle['velocity'][i] = v*omega + v1 + v2
        if particle['velocity'][i] > max_v:
            particle['velocity'][i] = max_v
        if particle['velocity'][i] < -max_v:
            particle['velocity'][i] = -max_v
开发者ID:fox000002,项目名称:PyCleverAlgorithms,代码行数:11,代码来源:pso.py

示例5: __init__

    def __init__(self, retention):
        self.retention = retention

        for x in range(0, self.initial_amount):
            new_user = User()
            new_user.idle = random.random() < retention
            self.users.append(new_user)
开发者ID:lszperling,项目名称:retention_simulation,代码行数:7,代码来源:simulation_generator.py

示例6: runcmd_threadpool

def runcmd_threadpool(cm,runwith):
    shell = 'bash'
    #runwith ='ssh [email protected] srun /bin/bash '
    if len(runwith) > 0:
        match = re.search('([\w.-]+)@([\w.-]+)', runwith)
        if match:
            username = match.group(1)
            curruser = getpass.getuser()
            if curruser != username:
                reps = {curruser:username}
                cm = replace_all(cm, reps)
        cmd= '%s "%s -c \'%s\' "' % (runwith[:-1],shell,cm[:-1])
    else:
        cmd= '%s -c \'%s\' ' % (shell,cm[:-1])

    s,o = commands.getstatusoutput(cmd)
    if s != 0:
        print 'problem running: ', cmd
        print 'output : ',o
        errfn='./%s/%d-cmd-%03d.txt'% ('.',os.getpid(),random.random())
        print 'wrote log to %s ' % errfn
        f = open(errfn, 'w')
        f.write( 'problem running: %s' % cmd)
        f.write('output : %s' % o)
        f.close()
    return 0
开发者ID:NickDaniil,项目名称:structured,代码行数:26,代码来源:runtp_dist.py

示例7: runIC2

def runIC2(G, S, p=.01):
    ''' Runs independent cascade model (finds levels of propagation).
    Let A0 be S. A_i is defined as activated nodes at ith step by nodes in A_(i-1).
    We call A_0, A_1, ..., A_i, ..., A_l levels of propagation.
    Input: G -- networkx graph object
    S -- initial set of vertices
    p -- propagation probability
    Output: T -- resulted influenced set of vertices (including S)
    '''
    from copy import deepcopy
    import random
    T = deepcopy(S)
    Acur = deepcopy(S)
    Anext = []
    i = 0
    while Acur:
        values = dict()
        for u in Acur:
            for v in G[u]:
                if v not in T:
                    w = G[u][v]['weight']
                    if random.random() < 1 - (1-p)**w:
                        Anext.append((v, u))
        Acur = [edge[0] for edge in Anext]
        print i, Anext
        i += 1
        T.extend(Acur)
        Anext = []
    return T
开发者ID:HengpengXu,项目名称:influence-maximization,代码行数:29,代码来源:IC.py

示例8: q

 def q(x):
     if x == min_bin:
         return min_bin + 1
     elif x == max_bin:
         return max_bin - 1
     else:
         return x- 1 if random.random() < .5 else x + 1
开发者ID:poneill,项目名称:gini_project,代码行数:7,代码来源:weighted_ensemble_method.py

示例9: sim_anneal

def sim_anneal(state,splits,merges):
    old_cost = cost(state,splits,merges)
    T = 10.0
    T_min = 0.01
    alpha = 0.97
    iterations = 500
    old_cost_plot = []
    new_cost_plot = []
    oplist = [1,2]

    while T > T_min:
        i = 1
        if i <= iterations:
            if i < 4*iterations/5.0 :
                operator = choice(oplist)
                if operator==1:
                    [new_state,new_splits,new_merges] = neighbor_switch_jumps(state,splits,merges)
                else:
                    [new_state,new_splits,new_merges] = look_ahead(state,splits,merges)
            else:
                new_state,new_splits,new_merges = neighbor_merge_split(state,splits,merges)
            new_cost = cost(new_state,new_splits,new_merges)
            ap = acceptance_probability(old_cost, new_cost, T)
            print('new cost: ' +str(new_cost) +' vs old cost: '+ str(old_cost))
            if ap > random.random() and old_cost != new_cost:
                print('accepted')
                state = deepcopy(new_state)
                splits=new_splits
                merges=new_merges
                plot(state,splits,merges)
                old_cost = new_cost
            i += 1
            T = T * alpha
    return state,splits,merges,old_cost
开发者ID:stellastyl,项目名称:trackingfoci,代码行数:34,代码来源:tracking_2.py

示例10: add_informe

 def add_informe(self, date):
     
     ''' 
     figure out the last date
     '''
     list_fechas = self.__finacial_inform.keys()
     list_fechas_order = list_fechas.sort()
     fecha_anterior = list_fechas_order[-1]
     
     '''
     new account year:
         frist, it was good (>0.5) or bad year, improve = generate better range of
         bad year company less money =  0.9
         good year company improve, more money= 1.1  
         then change the value 
     '''
     
     if random.random() < 0.5:
         value = 0.9
     else:
         value = 1.1
     
     self.__finacial_inform[date] = financial_inform(value*self.__finacial_inform[fecha_anterior]._activo_inm,
                                                      value*self.__finacial_inform[fecha_anterior]._activo_cir,
                                                      value*self.__finacial_inform[fecha_anterior]._pasivo_lar,
                                                      value*self.__finacial_inform[fecha_anterior]._pasivo_cor,
                                                      value*self.__finacial_inform[fecha_anterior]._ingresos,
                                                      value*self.__finacial_inform[fecha_anterior]._costes,
                                                      value*self.__finacial_inform[fecha_anterior]._amortia,                          
                                                     )
开发者ID:yethi,项目名称:Python,代码行数:30,代码来源:company.py

示例11: getRandom

	def getRandom(min, max, k):

		ints = dict()
		k -= 1
		while k >= 0:
			ints.update(  math.floor(min + (max-min)*random.random())  )
			k -= 1
		return ints
开发者ID:brianla,项目名称:WineApp,代码行数:8,代码来源:TopNRecommenderTest.py

示例12: update

    def update(obj, event):
        if l.getIteration() < args.steps and l.getIteration() > 0:
            # add the new point
            points.InsertPoint(l.getIteration(), l.getValue())
            points.Modified()
    
            # and update the lines accordingly
            lines.InsertNextCell(2)
            lines.InsertCellPoint(l.getIteration()-1)
            lines.InsertCellPoint(l.getIteration())
            lines.Modified()
    
        else:
            sigma, r, b = randomLorenzParameters()
            print "starting with new parameters (sigma, r, b) = ", sigma, r, b
            l.setParams(sigma, r, b)
    
            # reset the points array, does not free the space
            # and therefore makes sure we don't always allocate/free memory
            points.Reset()
            points.InsertPoint(l.getIteration(), l.getValue())
            points.Modified()

            # ... and do the ame for the lines
            lines.Reset()
            lines.InsertNextCell(1)
            lines.InsertCellPoint(0)
            lines.Modified()

            # let the actor paint in a new random color
            actor.GetProperty().SetColor(random.random(), random.random(), random.random())

        if not l.eval():
            import sys.exit
            exit(1)

        # resets the camera (only "zoom out") to include the complete line
        ren.ResetCamera()

        # and rotate the view a little (we could have used Yaw instead to rotate the scene instead of the camera)
        ren.GetActiveCamera().Azimuth(0.5)

        # the obj is the RenderWindowInteractor since the callback was registered for it
        # render again
        obj.GetRenderWindow().Render()
开发者ID:dev-zero,项目名称:computational-science-exercises,代码行数:45,代码来源:lorenz.py

示例13: mutate

def mutate(individual, mutation_rate):
    """ (list of int, double) -> list of int
    
    Return the individual which mutated each parameter with the chance given by the mutation_rate.
    """
    for j in xrange(len(individual)):
        if random.random() < mutation_rate:
            individual[i] = (individual[i] + 1) % 2
    return individual
开发者ID:cipo7741,项目名称:lectures,代码行数:9,代码来源:iterated-prisoners-dilemma.py

示例14: mutate

 def mutate(ind):
     if len(ind) < 2:
         raise TypeError("Individuum too short")
     for i in range(len(ind)):
         if random.random() < 1/len(ind):
             if ind[i] == '0':
                 replace = '1'
             else:
                 replace = '0'
             ind = ind[:i] + replace + ind[i+1:]
开发者ID:optNGUI,项目名称:Projekt-KI,代码行数:10,代码来源:algorithms.py

示例15: mutate

def mutate(an_individual, p):
    """
    Change each bit by chance p
    
    individual: the individual to mutate
    p: probability for each parameter to mutate    
    """
    for i in xrange(len(an_individual)):
        if random.random() < p:
            an_individual[i] = not an_individual[i]
    return an_individual
开发者ID:cipo7741,项目名称:lectures,代码行数:11,代码来源:simple-one-plus-one-es.py


注:本文中的random.random.random函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。