25

I wanted to generate 1 or -1 in Python as a step to randomizing between non-negative and non-positive numbers or to randomly changing sign of an already existing integer. What would be the best way to generate 1 or -1 in Python? Assuming even distribution I know I could use:

import random

#method1
my_number = random.choice((-1, 1))

#method2
my_number = (-1)**random.randrange(2)

#method3
# if I understand correctly random.random() should never return exactly 1
# so I use "<", not "<="
if random.random() < 0.5:
    my_number = 1
else:
    my_number = -1

#method4
my_number = random.randint(0,1)*2-1

Using timeit module I got the following results:

#method1
s = "my_number = random.choice((-1, 1))"
timeit.timeit(stmt = s, setup = "import random")
>2.814896769857569
#method2
s = "my_number = (-1)**random.randrange(2)"
timeit.timeit(stmt = s, setup = "import random")
>3.521280517518562
#method3
s = """
if random.random() < 0.5: my_number = 1
else: my_number = -1"""
timeit.timeit(stmt = s, setup = "import random")
>0.25321546903273884
#method4
s = "random.randint(0,1)*2-1"
timeit.timeit(stmt = s, setup = "import random")
>4.526625442240402

So unexpectedly method 3 is the fastest. My bet was on method 1 to be the fastest as it is also shortest. Also both method 1 (since Python 3.6 I think?) and 3 give the possibility to introduce uneven distributions. Although method 1 is shortest (main advantege) for now I would choose method 3:

def positive_or_negative():
    if random.random() < 0.5:
        return 1
    else:
        return -1

Testing:

s = """
import random
def positive_or_negative():
    if random.random() < 0.5:
        return 1
    else:
        return -1
        """
timeit.timeit(stmt = "my_number = positive_or_negative()", setup = s)
>0.3916183138621818

Any better (faster or shorter) method to randomly generate -1 or 1 in Python? Any reason why would you choose method 1 over method 3 or vice versa?

1
  • 2
    Method 3 is fastest because all the other methods have to do something like that internally.
    – Barmar
    Oct 18, 2017 at 22:38

8 Answers 8

23

A one liner variation of #3:

return 1 if random.random() < 0.5 else -1

It's fast(er) than the 'math' variants, because it doesn't involve additional arithmetic.

12

Here's another one-liner that my timings show to be faster than the if/else comparison to 0.5:

[-1,1][random.randrange(2)]
5
  • I tested this - it is not faster. timeit.timeit(stmt = "my_number = 1 if random.random() < 0.5 else -1", setup = "import random") >0.17129717730503558 and timeit.timeit("my_number = [-1,1][random.randrange(1,2)]",setup= "import random") >2.5639535604734647
    – Siemkowski
    Oct 20, 2017 at 13:10
  • @Siemkowski Your range specification is different than mine, and there may be differences between various versions of Python.
    – pjs
    Oct 20, 2017 at 13:21
  • sorry, pasted wrong line, but it is still slower for me. I use Python 3.6.1. What version did you test it on?
    – Siemkowski
    Oct 20, 2017 at 13:23
  • @Siemkowski Python 2.7.10 on MacOS.
    – pjs
    Oct 20, 2017 at 13:32
  • I like the simplicity of this code. Don't care about the difference in performance as much in my scenario - thanks! (:
    – Rikki
    Apr 18, 2021 at 5:51
7

not sure what your application is exactly, but I needed something similar for a large vectorized array.

Here's a good way to get a sign array:

(2*np.random.randint(0,2,size=(your_size))-1)

The result is an array, for example:

array([-1, -1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1])

and you can use the reshape command to get the above to the size of your matrix:

(2*np.random.randint(0,2,size=(m*n))-1).reshape(m,n)

Then you can multiply a matrix by the above and get all of the members with random signs.

A= np.array([[1, 2, 3], [4, 5, 6]])

B = A*(2*np.random.randint(0,2,size=(2*3))-1).reshape(2,3)

Then you get something like :

B = array([[ 1, 2, -3],[ 4, 5, -6]])

Pretty quick, if your data is vectorized.

6

Maths made simple:

  1. Generate random number: 0 or 1
  2. Get them mutiplied by 2: 0 or 2
  3. Substract 1: -1 or 1

Adapt that to any programming code. No need for test functions.

print(random.randint(0,1)*2-1)

works also without randint

print(int(random.random()*2)*2-1)
2

The fastest way to generate random numbers if you're going to be doing lots of them is by using numpy:

In [1]: import numpy as np

In [2]: import random

In [3]: %timeit [random.choice([-1,1]) for i in range(100000)]
10 loops, best of 3: 88.9 ms per loop

In [4]: %timeit [(-1)**random.randrange(2) for i in range(100000)]
10 loops, best of 3: 110 ms per loop

In [5]: %timeit [1 if random.random() < 0.5 else -1 for i in range(100000)]
100 loops, best of 3: 18.4 ms per loop

In [6]: %timeit [random.randint(0,1)*2-1 for i in range(100000)]
1 loop, best of 3: 180 ms per loop

In [7]: %timeit np.random.choice([-1,1],size=100000)
1000 loops, best of 3: 1.52 ms per loop
5
  • At least the last one doesn't only return -1,+1. Oct 18, 2017 at 23:25
  • isn't the last one (7) equivalent to random.choices([-1,1], k=100000) in random module?
    – Siemkowski
    Oct 19, 2017 at 8:35
  • @Siemkowski There was an edit, and the comment above referred to (8) i suppose.
    – sascha
    Oct 19, 2017 at 11:09
  • @sascha I know, I am referring to (7)
    – Siemkowski
    Oct 19, 2017 at 11:14
  • Yes it is. But python's random module is not numpy's random module.
    – sascha
    Oct 19, 2017 at 11:15
1

If you need single bits (one per call), you already did your benchmark and other answers provide additional info.

If you need many bits or can pre-calculate bit-arrays for later consumption, numpy's methods might shine.

Here is some more demo-approach using numpy (which surprisingly does not have a method dedicated for this job exactly):

import numpy as np
import random

def sample_bits(N):
    assert N % 8 == 0  # demo only
    n_bytes = N // 8

    rbytes = np.random.randint(0, 255, dtype=np.uint8, size=n_bytes)
    return np.unpackbits(rbytes)

def alt(N):
    return np.random.choice([-1,1],size=N)

def alt2(N):
    return [1 if random.random() < 0.5 else -1 for i in range(N)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("sample_bits(1024)", setup="from __main__ import sample_bits", number=10000))
    print(timeit.timeit("alt(1024)", setup="from __main__ import alt", number=10000))
    print(timeit.timeit("alt2(1024)", setup="from __main__ import alt2", number=10000))

Output:

0.06640421246836543
0.352129537507486
1.5522800431775592

The general idea is:

  • use numpy to generate many uint8's in one step
    • (there might be something better using internal functions without the randint-API)
  • unpack uint8's to 8 bits
    • uniformity follows from randint's uniformity guarantees

Again, this is only a demo:

  • for one specific case
  • not caring about different result-types of these functions
  • not caring about -1 vs. 0 (might be important in your use-case)
  • (not even optimal compared to much more low-level approaches; MT used internally can be used as a bit-source, which does not need fp-math, like many other PRNGs!)
0

random.randrange(-1,3,2)
prints a random number -1 or 1.
Remember "import random".
Explanation: https://www.w3schools.com/python/ref_random_randrange.asp

-4

My code is as

vals = array("i", [-1, 1])

def my_rnd():
    return vals[randint(0, 7) % 2]
2
  • 1
    Why use randint(0, 7) % 2 instead of just randint(0, 1)?
    – Barmar
    Oct 18, 2017 at 22:40
  • My test shows this slower than all the OP's options.
    – RobertB
    Oct 18, 2017 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.