Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose randomly between two values? [duplicate]

Tags:

python

numpy

So basically I'm trying to get a piece of code to randomly choose between two values -40 and 40.

To do so, I was thinking of using good old mathematics like -

random_num = ((-1)^value)*40, where value = {1, 2}.

random_num, as the name suggest should be a random number.

Any help ?

I am using python, solution using libraries is acceptable.

like image 419
DonutsSauvage Avatar asked Mar 28 '19 13:03

DonutsSauvage


1 Answers

If you want a random integer values between -40 and +40, then

import random
random.randint(-40, 40)

https://docs.python.org/3.1/library/random.html#random.randint

If you want to choose either -40 or +40, then

 import random
 random.choice([-40, 40])

https://docs.python.org/3/library/random.html#random.choice

If you really prefer to go with your implementation of choosing either 1 or 2, as in your question, then plug in those values in random.choice method.

Provided the above solutions, since I feel there is some ambiguity in the question.

like image 190
Kay Kay Avatar answered Oct 20 '22 16:10

Kay Kay