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']

转载于:https://www.cnblogs.com/xiaobingqianrui/p/8386617.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值