zoukankan      html  css  js  c++  java
  • python学习笔记之random模块

    random模块

    • 产生随机数

      # 产生随机整数 有a和b两个参数作为变化范围
      print(random.randint(1,10))	# 从1到10
      
    • 根据随机数种子产生随机小数

      # 设置固定随机种子后 就是假随机了,第一次结果永远固定
      random.seed(10)		# 设置随机数种子
      print(random.random())  # 取(0,1)之间的小数
      
      # 如果不自定义种子,则种子按照当前的时间来
      print(random.random())  # 取(0,1)之间的小数
      
    • choice函数

      print(random.choice([1,1,2,3,4]))	# 通过choice函数选择列表中的一个数
      
    • shuffle函数

      lt = [1,2,3,4]
      random.shuffle(lt)	# 通过shuffle函数打乱序列
      print(lt)
      

    使用时间模拟random随机数

    import time
    time_ = time.time()
    print(str(time_).split(".")[-1][-1])	# 使用切割时间尾数的最后一位做随机数
    

    圆周率计算

    • 圆周率近似计算公式

      pi = 0
      k = 0
      while True:		# 使用公式取近似计算
      	pi +=  (1/(16**k))* 
      		   (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))
      	print(pi)
      	k += 1
      
    • 蒙特卡洛方法求圆周率

      import random
      count = 0
      for i in range(100000):
      	x, y = random.random(), random.random()	// 使用随机数方式撒点
          dist = pow(x ** 2 + y ** 2, 0.5)		// 重要公式
          if dist < 1:
          	count += 1
      print(count / 100000 * 4)
      

  • 相关阅读:
    线上查询及帮助命令:
    windows: 2.7 3.5 (主要)
    get the execution time of a sql statement.
    java-kafka安装以及使用案例
    java-黑马头条 weex前端路由
    MYSQL安装
    缓存
    Flask中current_app和g对象
    [ValueError: signal only works in main thread]
    Flask-SQLAlchemy操作
  • 原文地址:https://www.cnblogs.com/XuChengNotes/p/11242054.html
Copyright © 2011-2022 走看看