起因
最近在学习机器学习,在使用numpy库学习的时候,遇到了这样一段代码:import randomimport timeimport numpy as npa = []for i in range(100000000): a.append(random.random())# 通过%time魔法方法, 查看当前行的代码运行一次所花费的时间%time sum1=sum(a)b=np.array(a)%time sum2=np.sum(b)
对其中的random.random()不明白, 将列表a打印出来得到的结果全是为0-1的浮点型数字.
答案
上网查阅random.random()的作用其实就是得到一个范围在(0,1)之间的随机数.例如:
import randoma = []for i in range(100): a.append(random.random())print(a)
- 结果
[0.09708702448570439, 0.5304248570653616, 0.5176375523206675, 0.3520787181584155, 0.38258879475327745, 0.40135233267863324, 0.19367900989828835, 0.9865108132276019, 0.8522765696726017, 0.16742741635616587, 0.26430494425592155, 0.1015033312690512, 0.6450790839149619, 0.7418636302770913, 0.9749876474987943, 0.9072925613370767, 0.08596414234737415, 0.38292495542491845, 0.6503490072702952, 0.6850905111819618, 0.6397125974143014, 0.24891447803031852, 0.02223912367720071, 0.7441341214246594, 0.8425122809340055, 0.5347277063716859, 0.32920370746602634, 0.08543311432925527, 0.28783996573751147, 0.21101968215023725, 0.9007854521244699, 0.35979682388777945, 0.4598560040925618, 0.6347311886269931, 0.28163261470847123, 0.986999068365047, 0.820726274173795, 0.6798989420944803, 0.8403149180385441, 0.23203070873690146, 0.0981825955128649, 0.9522108658489729, 0.04123129781077839, 0.9324134121427093, 0.2833412982685367, 0.6023590586499595, 0.7840238656760544, 0.7676234905634307, 0.39984028672438987, 0.4959285655117398, 0.5126732516479778, 0.763281169424597, 0.525487671564804, 0.24417205079187954, 0.9472156123555283, 0.31558024119665196, 0.33474839282331414, 0.40228075907861516, 0.29806507767715784, 0.021937589139880642, 0.5329103283786069, 0.833560052105248, 0.43975327335727454, 0.7041089093209378, 0.25650176351700493, 0.7048085932687687, 0.856437910896548, 0.12477651530491207, 0.5293359143289389, 0.2963485692398722, 0.48691394090484574, 0.5324293957846951, 0.3368547780943648, 0.02747979709591708, 0.636390145880627, 0.8760394324116636, 0.8493516720451669, 0.8852208630015503, 0.562985430395568, 0.7619880510756081, 0.6941282159667079, 0.1540610037633312, 0.1071152994500506, 0.18463277576335357, 0.43194433535952237, 0.708580546834265, 0.844931036834706, 0.18392490027597974, 0.9245090973228666, 0.2604862909971223, 0.10870052763429372, 0.43676768256634135, 0.17890560094867014, 0.014194889887072404, 0.2905242954475158, 0.06807080177071945, 0.6765490043972644, 0.4177307353744367, 0.24943208230308422, 0.060237055121637684]
参数
同样,我们也可以在random()函数中添加参数,例如random(1,10),得到的将是随机生成一个1-10的随机数.