python中如何生成随机数的几个例子

 1 #__author:"吉勇佳"
 2 #date: 2018/10/14 0014
 3 #function:
 4 
 5 import math
 6 import random
 7 
 8 # 向上取整
 9 print(math.ceil(18.1))
10 
11 '''
12 输出:
13 19
14 '''
15 
16 # 向下取整
17 print(math.floor(18.1))
18 
19 '''
20 输出:
21 18
22 '''
23 
24 # 返回整数与小数
25 print(math.modf(22.3))
26 
27 '''
28 输出
29 (0.3000000000000007, 22.0)
30 '''
31 
32 # 开平方
33 print(math.sqrt(16))
34 
35 '''
36 返回:
37 4.0
38 '''
39 
40 # 随机数
41 # 方法1:从序列的元素中随机取出一个数字来
42 print(random.choice([1,3,4,5,6,7,8,9,4,3,2,22,13,445,3,2,3]))
43 
44 # 方法2 :从range范围内取值
45 print(random.choice(range(1,100)))
46 
47 # 方法3:从字符串中随机取
48 print(random.choice("jiyongjia"))
49 
50 # 方法4:从多个字符串的列表中随机取
51 print(random.choice(["jiyongjia","sunxin","zhanglei "]))
52 
53 
54 # 方法5:用randrange方法
55 print(random.randrange(1,100,2))
56 
57 # 方法6:取出随机的一个整形数字
58 print(random.randint(1,100))
59 
60 # 方法7:随机的0-1之间的数字
61 print(random.random())
62 
63 # 方法8:将序列的元素随机排序
64 list=[1,2,3,4,5,6,7]
65 random.shuffle(list)
66 print(list)
67 '''
68 输出:
69 [1, 4, 2, 5, 3, 6, 7]
70 '''

# 方法9 :随机产生一个实数
print(random.uniform(3,19))
'''
输出:
3.327772693472834
'''
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/jiyongjia/p/9786358.html