我想使用random.random()生成随机浮点数并使用一些数学修改输出,以便最终得到-100到+100.使用数学我想使用乘法和减法来生成-100到+100范围内的三个随机浮点数.
这是我的代码:
import random random_float = (random.random()) print("First random float between -100 and +100:", random_float - 10) print("Second random float between -100 and +100:", random_float * 70) print("Third random float between -100 and +100:", random_float * 100)
这是我的输出:
First random float between -100 and +100: -9.932043497731886 Second random float between -100 and +100: 4.756955158768027 Third random float between -100 and +100: 6.795650226811468
这看起来不错吗?
你可以使用random.uniform(a,b)
:
random.uniform(-100,100)
如果你绝对想自己计算:
random.random()*200-100你的代码
以下是将其集成到代码中的方法.请注意,random
如果您想要独立的随机数,则需要调用三次:
import random for ordinal in ['First', 'Second', 'Third']: random_float = random.uniform(-100,100) print "%s random float between -100 and +100: %f" % (ordinal, random_float)
它输出:
First random float between -100 and +100: -67.216959 Second random float between -100 and +100: 25.984499 Third random float between -100 and +100: 60.656098