zingy
zingy

Reputation: 811

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

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.html

Upvotes: 11

Views: 19247

Answers (6)

user78692
user78692

Reputation: 71

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)

Upvotes: 1

brandizzi
brandizzi

Reputation: 27050

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]

Upvotes: 10

Wooble
Wooble

Reputation: 89927

>>> 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().

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308206

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

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

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

Also, take a look at decimal.

Upvotes: 6

Patrick87
Patrick87

Reputation: 28302

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.

Upvotes: 0

Related Questions