View Single Post
  #10   Report Post  
Posted to microsoft.public.excel.programming
John Coleman John Coleman is offline
external usenet poster
 
Posts: 274
Default Randomize three variables subject to sum always equal to 1

emsfeld wrote in message ...
Hi guys

I need a hand on this one, cuz I have absolutely no clue:

I need a code that randomly selects three real numbers between 0 and 1
and assigns these to three variables. I defined the variables as w(0),
w(1), w(2). The problem is that the sum has to equal 1! Always! So
that:

w(0) + w(1) + w(2) = 1

Help is very much appreciated!!!

Thanks

Emsfeld



Greetings
As other posters have pointed out, there in more than 1 way to answer
depending on what you are looking for. A very easy way is to imagine
the 3 numbers as being the result of two random cuts, where the random
cuts are uniformly distributed in [0,1]:
something like

cut1 = rnd()
cut2 = rnd()
if cut1 cut2 then
temp = cut1
cut1 = cut2
cut2 = temp
end if
w(0) = cut1
w(1) = cut2 - cut1
w(2) = 1 - cut2

works.

On the other hand, what you are asking for might be the following:
pick a point (x,y,z) at random which satisfies x,y,z = 0 and x + y +
z = 1. Then you are talking about picking a point at random
(presumably uniformly) from an equilateral triangle with sides sqrt(2)
which is situated in 3-D space. A crude algorithm would be to first do
this for a triangle situated in the plane (perhaps by a hit-miss
approach - embed the triangle in a square with sides sqrt(2) and
select points from the square at random (easy) until you get 1 that
hits the triangle, on average 2 or 3 attempts will suffice) and then
apply a linear transformation to get your point in 3-space. I'm sure
that better algorithms exist but this will work and won't be too hard
to code, though not worth the effort if it isn't what you want. If you
want - I can try to code it and might do so tomorrow for fun anyway.

Hope this helps

-John Coleman

---
Message posted from http://www.ExcelForum.com/