开发者

how to create a range of random decimal numbers between 0 and 1

开发者 https://www.devze.com 2023-03-24 03:01 出处:网络
how do I define decimal range between 0 to 1 in python? Range() function in python returns only int values. I have some variables in my code whose number varies from 0 to 1. I am confused on how do I

how do I define decimal range between 0 to 1 in python? Range() function in python returns only int values. I have some variables in my code whose number varies from 0 to 1. I am confused on how do I put that in the code. Thank you

I would add more to my question. There is no step or any increment value that would generate the decimal values. I have to use a variable which could have a value from 0 to 1. It can be any value. But the program should know its boundary that it has a range from 0 to 1. I hope I made myself clear. Thank you

http://docs.python.org/library/random.h开发者_如何学JAVAtml


If you are looking for a list of random numbers between 0 and 1, I think you may have a good use of the random module

>>> import random
>>> [random.random() for _ in range(0, 10)]
[0.9445162222544106, 0.17063032908425135, 0.20110591438189673,
 0.8392299590767177, 0.2841838551284578, 0.48562600723583027,
 0.15468445000916797, 0.4314435745393854, 0.11913358976315869,
 0.6793348370697525]


for i in range(100):
    i /= 100.0
    print i

Also, take a look at decimal.


def float_range(start, end, increment):
    int_start = int(start / increment)
    int_end = int(end / increment)
    for i in range(int_start, int_end):
        yield i * increment


This will output decimal number between 0 to 1 with step size 0.1

import numpy as np
mylist = np.arange(0, 1, 0.1)


It seems like list comprehensions would be fairly useful here.

  mylist = [x / n for x in range(n)]

Something like that? My Python's rusty.


>>> from decimal import Decimal
>>> [Decimal(x)/10 for x in xrange(11)]
[Decimal("0"), Decimal("0.1"), Decimal("0.2"), Decimal("0.3"), Decimal("0.4"), Decimal("0.5"), Decimal("0.6"), Decimal("0.7"), Decimal("0.8"), Decimal("0.9"), Decimal("1")]

Edit, given comment on Mark Random's answer:

If you really don't want a smoothly incrementing range, but rather a random number between 0 and 1, use random.random().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号