Ask coding questions

← Back to all posts
Random Numbers with Arbitrary Probability Distribution (Python 3)
OwenBradstreet (112)

So I want to generate a random number, for example between 1-100. I want the probability of 100 being generated to be way more likely than 1, going up like that. The greater the number is, the more likely it is to be generated.

If it helps to have some context, I'm making a game where weapons have an accuracy. The higher the accuracy, the more chance there is of the weapon hitting the target, but I still want it to be (however remotely) possible for the weapon to miss, even if the accuracy is really high.

I've done some research into APD, but not found much in the way of a solid solution. Can anyone help?

Thanks.

Commentshotnewtop
haakenlid (1)

How about this: 101 - math.floor(101 ** random.random())
It will give some sort of inverse logarithmic distribution.

OwenBradstreet (112)

@haakenlid That's a nice idea - more efficient in terms of lines. I haven't tested it but it looks like that should work, thanks!

OwenBradstreet (112)

So, thanks to the brilliant mind of timchen, the solution is as simple as:

import random

accuracy = int(input("Accuracy (1-100): "))
randomNumber = random.randint(1,101)
if accuracy > randomNumber:
    print("Hit!")
else:
    print("Miss!")

Awesome community here :)