如何计算生成的平均随机数?

时间:2016-02-26 22:46:12

标签: python python-2.7 python-3.x

我编写了一个FOR循环来调用一个函数100次以得到100个随机数,我现在需要计算生成的所有随机数的平均数。我怎样才能做到这一点?这是我到目前为止所处的地方

import random

num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))

for i in range(10):
  print(random.uniform(num1, num2), end = "\t")

4 个答案:

答案 0 :(得分:4)

首先,您的功能仅运行10次。您需要存储正在生成的值,而不是将它们打印到屏幕上。您可以通过将其存储在列表中来完成此操作。

要获得100个随机变量的列表,您可以[random.uniform(num1, num2) for i in range(100)]

然后,你需要找到平均值。要获得总和,您可以sum(list)。要获取值的数量,请执行len(list)。如果我们将这些结合在一起,我们得到:

import random

num1 = int(input("Input First number: "))
num2 = int(input("Input Second number: "))

random_numbers = [random.uniform(num1, num2) for i in range(100)]
print(sum(random_numbers)/len(random_numbers))

输出是:

>>> import random
>>> num1 = int(input("Input First number: "))
Input First number: 10
>>> num2 = int(input("Input Second number: "))
Input Second number: 20
>>> random_numbers = [random.uniform(num1, num2) for i in range(10)]
>>> random_numbers
[13.083389212287019, 12.551686149990369, 13.881302022239865, 12.5156539109837, 12.340949073439575, 13.693758114264867, 13.972147752101735, 14.111313446849902, 11.693700678679372, 18.136716333128035]
>>> print(sum(random_numbers)/len(random_numbers))
13.5980616694

答案 1 :(得分:3)

import random
rand_nums = [random.uniform(num1, num2) for i in range(10)]
average = sum(rand_nums) / len(rand_nums) 

或者如果您更喜欢使用numpy

import numpy as np
rand_nums = np.random.uniform(num1,num2,10)
average = rand_nums.mean()

答案 2 :(得分:1)

我认为您必须将数字存储在某处,而不是打印它们。如果使用列表,则可以计算总和,然后除以长度。

import random

num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))

numbers = []
for i in range(10):
  numbers.append(random.uniform(num1, num2))

print(numbers)
print(sum(numbers)/len(numbers))

答案 3 :(得分:1)

这是非常基本的东西,希望这会有所帮助:

import random
num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))

sum = 0
numbers = 100
for i in range(numbers):
  random_number = random.uniform(num1, num2)
  sum += random_number
avarage = sum/numbers
print(avarage)