• Python之数学(math)和随机数(random)


    math包包含了最基本的数学运算函数,如果想要更加高级的数学功能,可以使用标准库外的numpy和scipy库,他们不但支持数组和矩阵运算,

    还有丰富的数学和物理方程可供使用

    random包可以用来生成随机数,随机数不仅可以用于数学用途,还经常被嵌入到算法中

    math包

      1. 常数

         math包主要处理数学相关的运算。math包定义了两个常数:

         math.e   # 自然常数e

         math.pi   # 圆周率pi

      2. 常用函数

         math.cell(x)     #对x向上取整

         math.floor(x)      #对x向下取整

         math.pow(x, y)          #x的y次方

         math.log(x)               #以e为低取对数

         math.sqrt(x)              #平方根

         math.sin(x),math.cos(x),math,tan(x),math.atan(x),math.asin(x),math.acos(x)

         math.degrees(x),math.radians(x)     #角度和弧度互换

         math.erf(x),math.gamma(x)              #特殊函数

    random包

      1. 常用函数

    • seed(a=none,version=2)
    • random()
    • randint(a,b)
    • uniform(a,b)
    • choice(x)
    • shuffle(x)
    • sample(x,y)

      2. 事例

    #coding=utf-8
    
    import random
    
    #生成随机浮点数(0,1)
    print ("random():",random.random())
    
    #生成随机1-10之间的整数
    print ("randint():", random.randint(1,10))
    
    #随机生成0-20之间的偶数
    print ("randrange:", random.randrange(0,21,2))
    
    #随机生成0-20之间的浮点数
    print("uniform:", random.uniform(0,20))
    
    #从列表序列中随机取一个数
    li = [1,2,3,4,5,6,7,8,9]
    print ("choice list:", random.choice(li))
    print ("choice string:", random.choice("abcdef"))
    
    #对列表元素随机排序
    print ("shuffle forword:", li)
    random.shuffle(li)
    print ("shuffle back:", li)
    
    #从指定序列中获取指定长度的片段
    print ("sample:", random.sample("abcedef", 3))

      3. 事例结果

        >> random(): 0.5133725183742832
        >>randint(): 4
        >>randrange: 6
        >>uniform: 3.0505739812897503
        >>choice list: 2
        >>choice string: a
        >>shuffle forword: [1, 2, 3, 4, 5, 6, 7, 8, 9]
        >>shuffle back: [4, 1, 2, 8, 6, 9, 3, 7, 5]
        >>sample: ['b', 'c', 'f']

  • 相关阅读:
    AFNet3.0上传图片
    最新 AFNetworking 3.0 简单实用封装
    iOS开发密码输入数字和字母混合
    IOS用CGContextRef画各种图形(文字、圆、直线、弧线、矩形、扇形、椭圆、三角形、圆角矩形、贝塞尔曲线、图片)(转)
    iOS开发探索-图片压缩处理
    常用第三方框架插件
    2.1创建直线
    1.4用向导创建Hello,world程序
    vs2008找不到ObjectARX MFC Support
    vc6.0错误:error C2653: 'CCreateEnt' : is not a class or namespace name
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8386617.html
Copyright © 2020-2023  润新知