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)
      

  • 相关阅读:
    台湾9大知名开源社区
    使用SignalR打造消息总线
    ENode 2.0
    Wireshark基本介绍和学习TCP三次握手 专题
    linux tomcat 的安装
    linux 之静默安装oracle
    什么是全栈呢(转)
    Android开发自学笔记(基于Android Studio1.3.1)—1.环境搭建(转)
    hdu 4919 Exclusive or
    D
  • 原文地址:https://www.cnblogs.com/XuChengNotes/p/11242054.html
Copyright © 2011-2022 走看看