Generating random numbers from 0 - 1 with limit on the sum
Show older comments
Hi,
I am trying to generate values from 0 to 1 for several variables (x1 x2 x3).
These results must assure that x1*a1 + x2*a2 + x3*a3 <= D. a1 a2 a3 and D are other variables I define. How can I do this?
Thank you very much,
2 Comments
Adam
on 15 Jul 2016
How random do you want the values to be? e.g. there are ways to easily ensure that the variables will obey the constraint, but in a ways that bias the variables in some way or another rather than allowing as much free choice as might be required.
e.g. obviously every x1, x2, x3 will be no larger than 1 so if you divide each random number by (a1 + a2 + a3) you will guarantee that your condition is met, but not necessarily in a satisfactory manner because it is simply using basic upper bound maths.
Alexandra
on 15 Jul 2016
Accepted Answer
More Answers (2)
Azzi Abdelmalek
on 14 Jul 2016
Edited: Azzi Abdelmalek
on 14 Jul 2016
a1=2
a2=3
a3=4
D=5
v=rand(1,2)
x1=v(1)
x2=v(2)
x3=rand*(D-a1*x1-a2*x2)/a3
Check
x1*a1 + x2*a2 + x3*a3<D
5 Comments
Alexandra
on 15 Jul 2016
Alexandra
on 15 Jul 2016
Edited: Azzi Abdelmalek
on 15 Jul 2016
Walter Roberson
on 15 Jul 2016
It does not matter that A2 is above 30: the last line of your code rescales x so if you were to recalculate A2 based upon the new x, you would get exactly 30.
John D'Errico
on 15 Jul 2016
Edited: John D'Errico
on 15 Jul 2016
ARGH. This answer is bad for several reasons.
It does not insure the sum is less than 30. It ensures that the sum IS 30.
The question was to have a solution such that the sum is NO GREATER THAN D.
As bad is the non-uniformity issue. Even if this solution were only applied to the set of points that fell above the limit, it would then have too many points packed on the hyper-plane at the limit.
Finally, even if the question was about forcing the sum to be exactly D, this quasi-solution would STILL be a bad idea, because it does not even result in a uniform sampling on the indicated hyper-plane.
So bad for three reasons. I'll post an answer that goes into some depth.
Alexandra
on 15 Jul 2016
Walter Roberson
on 15 Jul 2016
0 votes
If you were looking for exact equality with D, then you could probably adapt the code at https://www.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum to add in a weight vector, a
1 Comment
John D'Errico
on 15 Jul 2016
I recall looking at Roger's code, wanting to modify it for a general linear constraint. That might take some serious thought.
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





