user3055938
user3055938

Reputation: 323

Weight random number towards range

Let's say I'm getting random number in the range using:

random.randrange(100)

Let's say that if it gives a number less than or equal to 25, you win and if it gives a number greater than 25, I win. I would then have a 75% chance to win.

How can I weight the chances of the number being greater than 25 by some percentage, say 1%.

So basically I'm trying to tilt the odds of me winning by another 1%, without changing just saying, "you win at 24 or less."

Let me know if this is unclear.

Upvotes: 0

Views: 630

Answers (3)

Thadeu Melo
Thadeu Melo

Reputation: 991

If you want 1% of 25% you need to use a larger sample and use a value accordingly: 100000 and 249750.

Another solution is adding an if with a change of 1% winning if the player lost the first try.

if random.range(100) > 25
  return "You Win"
else
 if random.range(100) < 1
   return "You Win"
 else
  return "You Lose"

Upvotes: 1

John Y
John Y

Reputation: 14529

It seems you want "unfair" dice, so to speak.

One way to get this, if you know the desired odds of winning, is to first decide whether you win or not. If you win, then choose a number among the winning numbers. If you lose, choose a number among the losing numbers.

For example:

import random

def die_roll():
    if random.random() < 0.26:
        return random.randrange(25)  # 0 to 24
    return random.randrange(25, 100)  # 25 to 99

Upvotes: 2

Randy Hall
Randy Hall

Reputation: 8137

Get a random number smaller than your range. Say you want 1-100 with mostly 60s.

Random 1-5

When 1, random 60-69

Otherwise, random 1-100

Will be 28% 60s, if my math is correct

--z

For your example, I believe you'd want to random 1-100, then on 1 random 26-100. That's not exactly a 1% increase, but you can fiddle with the math to get the percents you want.

Upvotes: 1

Related Questions