Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

language agnostic - Getting N random numbers whose sum is M

I want to get N random numbers whose sum is a value.

For example, let's suppose I want 5 random numbers that sum to 1.

Then, a valid possibility is:

0.2 0.2 0.2 0.2 0.2

Another possibility is:

0.8 0.1 0.03 0.03 0.04

And so on. I need this for the creation of a matrix of belongings for Fuzzy C-means.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short Answer:

Just generate N random numbers, compute their sum, divide each one by the sum and multiply by M.

Longer Answer:

The above solution does not yield a uniform distribution which might be an issue depending on what these random numbers are used for. Another method proposed by Matti Virkkunen:

Generate N-1 random numbers between 0 and 1, add the numbers 0 and 1 themselves to the list, sort them, and take the differences of adjacent numbers.

This yields a uniform distribution as is explained here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...