RE: Sum of 15 random +/- integers always greater than or equal to

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Hi Tom:
Thanks very much for your post.
When I run your code, I get a compile error: 'Sub or Function not defined'
for v1 in the following line:
v1(v(i)) = v1(v(i)) + 1

I apologize, but I don't have enough VBA experience to debug the code. I'm
guessing it's a simple fix...

Mike



"Tom Ogilvy" wrote:

As Jerry says, the chance it will be positive is around 50%, so you could
just generate the numbers until they sum to a positive value.

Sub ABCD()
Dim bd As Long
Dim i As Long
bd = 99999
Dim v(1 To 15) As Long
Dim tot As Long
Do
tot = 0
For i = 1 To 15
v(i) = Int(Rnd() * ((bd + 0.5) * 2) - (bd))
v1(v(i)) = v1(v(i)) + 1
tot = tot + v(i)
Next
Loop Until tot >= 0
Range("A1").Resize(15, 1) = Application.Transpose(v)
End Sub

--
Regards,
Tom Ogilvy

"MikeM" wrote:

Hi Jerry:
Thanks for responding.
I suppose I was thinking along the lines of generating the first random
integer in cell B4. Then, the next step would be to generate a random
integer in cell B5. The code would then SUM B4:B5 and ascertain if the
result were >= zero. If yes, it would proceed to the next cell in the range,
B6. If no, it would generate a new random value for B5 and apply the same
test again until it was successful. For each successive random value the SUM
test range would expand to include the new value.

I think that's what you were saying in your choice of constraints:
"- throw it away and draw again until the sum is non-negative"

Hope this helps. And thanks for your interest!

Mike


"Jerry W. Lewis" wrote:

If they were independent identically distributed discrete uniform random
integers, then the probability of a negative sum would be nearly 0.5. How do
you want to constrain the "randomness" to ensure that the sum is not
negative? Some possibilities if the 15th value produces a negative sum would
include,
- replace the 15th value with -SUM(fourteenValues)
- throw it away and draw again until the sum is non-negative
...
Note that the 1st option can result in a value larger than 99,999, in which
case the 2nd option would never terminate.

Jerry

"MikeM" wrote:

Howdy:
What I'd like to do is the following:
Generate a column of 15 random integers from -99,999 to +99,999
The sum of these 15 random integers must be greater than or equal to zero.

Thanks.

Mike
.



Relevant Pages