How to Choose Randomly Between Two Values? [Duplicate]
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...
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.
If you want a random integer values between -40 and +40, then
import random
random.randint(-40, 40)
If you want to choose either -40 or +40, then
import random
random.choice([-40, 40])
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.
Assuming that L is a list of values you want to choose from, then random.choice(L) will do the job.
In your case:
import random
L = [-40, 40]
print(random.choice(L))
It is simple in Python:
Python 3.7.3 (default, Mar 27 2019, 13:36:35)
[GCC 9.0.1 20190227 (Red Hat 9.0.1-0.8)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from random import choice
>>> choice((-40, 40))
40
>>>
You can use the choices function in python to achieve this. If you want values to be chosen to be only -40 or 40, the second argument is the probability/weights.
from random import choices
choices([-40,40], [0.5,0.5])