L
L
likeviolence2020-11-30 00:23:56
Python
likeviolence, 2020-11-30 00:23:56

Random algorithm in which the larger the number, the lower the chance of it falling out?

There is some variable - the wear of a thing, which is a number with two digits after the decimal point and a maximum value equal to: 99.99, how to make it random so that the higher this number, the lower the chance of falling out.
I did it through random ranges:
random(0,1000)
if the result is from 0 to 500 then randomly from 0 to 70
0 - 500 -> random(0, 70) and so on, but this is not very suitable, since the chance of falling out, for example, 90 and 99 are too equal, and writing each number is too long

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2020-11-30
@likeviolence

You random.choiceshave the ability to set the "weight" for the elements. For example:

import random

item_chances = {
    'item_1': 10,
    'item_2': 30,
    'item_3': 50,
    'item_4': 70,
    'item_5': 90
}

selected = random.choices(
    list(item_chances.keys()), weights=list(item_chances.values()), k=5000)

for item in set(selected):
    print(f'{item}: {selected.count(item)}')

Here, y has item_1the smallest weight, that is, the smallest chance of getting this value, while y has item_5the highest. The argument kspecifies how many elements to select. In this case, I chose 5000 for the test. Conclusion:
item_1: 175
item_2: 578
item_3: 1001
item_4: 1458
item_5: 1788

As you can see, everything converges and "objects" fell out according to their "weight".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question