• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python random.random函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: generate_weights

def generate_weights(layers):
   input_layer_size = layers[0]
   output_layer_size = layers[len(layers)-1]
   hidden_layers = layers[1:len(layers)-1]
   thetas = []
   prevSize = input_layer_size
   for i in range(0,len(hidden_layers)):
      eint = sqrt(6)/sqrt(prevSize + hidden_layers[i])
      temp = []
      for j in range(0,(hidden_layers[i] * (prevSize + 1))):
         temp.append(random.random() * 2 * eint - eint)
      thetas.append(array(temp))
      thetas[i].resize(hidden_layers[i],(prevSize + 1))
      prevSize = hidden_layers[i]
   eint = sqrt(6)/sqrt(prevSize + output_layer_size)
   temp = []
   for j in range(0,output_layer_size * (prevSize + 1)):
      temp.append(random.random() * 2 * eint - eint)
   thetas.append(array(temp))
   thetas[len(thetas)-1].resize(output_layer_size,(prevSize + 1))
   return thetas
开发者ID:numberten,项目名称:scribble-recognition,代码行数:21,代码来源:NN2.py


示例17: mutate

 def mutate(self, mutate_prob, parents):
     """
     Add or subtract 0.01 from every solution that is going to be mutated
     the sign of the operation is decided at random with .5 probability
     at each option (.5 for + and .5 for -)
     """
     for i in range(len(parents)):
         if mutate_prob > random.random():
             if random() > 0.5:
                 parents[i] += 0.01 if parents[i] <= 0.99 else 0.0
             else:
                 parents[i] -= 0.01 if parents[i] >= 0.01 else 0.0
开发者ID:pierorex,项目名称:pygen,代码行数:12,代码来源:dialer_optimizer.py


示例18: vector

def vector(base_seq, mut_factor, CDR_list):
    """base_seq - sequense in str format,
    mut_factor in range (0,1)
    return vector of integers"""
    vector = []
    list_ref = [translator(i) for i in base_seq]
    for i in range(len(list_ref)):
        if i not in CDR_list and mut_factor > random.random() and list_ref[i] not in ['C', 2]:
            vector.append(translator(res_choice()))
        else:
            vector.append(list_ref[i])
    return vector
开发者ID:LaFemmeMarie,项目名称:re-Search,代码行数:12,代码来源:gen_alg_struct_align.py


示例19: acceptance

def acceptance(E1,E2):
    if E2<E1:
        return True
    elif E2>E1:
        #probability
        pr = np.exp(-beta*(E2-E1))
        #choosing a random number to check with the probability distribution
        ran = random.random()
        if ran < pr:
            return True
        elif ran > pr:
            return False
开发者ID:Andromedanita,项目名称:PHY407,代码行数:12,代码来源:lab11_q3.py


示例20: runcmd_threadpool

def runcmd_threadpool(cm):
    cmd= 'csh -c \'%s\'' % 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,代码行数:13,代码来源:runtp.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python random.shuffle函数代码示例发布时间:2022-05-26
下一篇:
Python random.choice函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap