Skip to content
Advertisement

Python: generate 5 random int (every has own range) with fixed sum

JavaScript

Each value in Total has own range (in %).

First: find random values (within ranges that is % from Total.).

I tried this (but sum() can be >or< than 100):

JavaScript

Second:find exact value for a,b,c,d,e (according to the percentage from Total in First part). I tried this:

JavaScript

This code does not work. please help

Advertisement

Answer

I’d start with the smallest ranges first, then pick the last one not randomly but as the difference between the sum of the other 4 and 100. Since random numbers can’t be guaranteed to meet all the constraints, you may need to keep picking until you get a satisfactory answer.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement