Py学习  »  Python

在python中创建随机数生成器程序[副本]

Amirhosein Jalili • 4 年前 • 160 次点击  

所以我需要在python中创建一个for循环来生成随机实数,在这个循环中,一旦这些随机实数被选中,将在后面被平方。帮助?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38121
 
160 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Tigert
Reply   •   1 楼
Tigert    8 年前
import random
count = 10 #how many numbers do you want
for i in range(0, count):
   r = random.random() #generates random real number between 0 and 1
   print r**2 #prints squared number

对于伪随机数,有“随机”模块。

我不知道你期望的数字有多大,但是 random.random() 会给你0到1之间的数字。

您可以查看此页面 more information

最后,在python中对数字进行平方很简单 x**2

Thomas W
Reply   •   2 楼
Thomas W    8 年前

如果你想在一次内得到一个更长的整数,你可以这样做:

randomNumber = random.randint(a,b)

#To square the number:

randomNumber = randomNumber ** 2

确保导入 random .

您的整个代码将是:

import random

numbers = []

#NUMBER is whatever amount of numbers you want
for i in range(NUMBER):
    rnumber = random.randint(a,b) #a,b are maxima
    rnumber = rnumber ** 2
    numbers.append(rnumber)

在哪里? a 是最小的int和 b 是最大整数。它将在 .

使用 random.uniform() 而不是 random.randint() 如果您还想包括浮动。

twinlakes
Reply   •   3 楼
twinlakes    8 年前

这个 random 函数来自 随机的 模块将随机返回 float 在0到1之间,根据美丽的 documentation .