我是靠谱客的博主 丰富灰狼,最近开发中收集的这篇文章主要介绍python生成和为1的随机数_生成一个总和为1的随机数序列?,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I am at my wit''s end.

I want to generate a certain number of random numbers.

This is easy, I can repeatedly do uniform(0, 1) for

example.

But, I want the random numbers just generated sum up

to 1 .

I am not sure how to do this. Any idea? Thanks.

__________________________________________________

Do You Yahoo!?

Tired of spam? Yahoo! Mail has the best spam protection around

http://mail.yahoo.com

解决方案Anthony Liu wrote:I am at my wit''s end.

I want to generate a certain number of random numbers.

This is easy, I can repeatedly do uniform(0, 1) for

example.

But, I want the random numbers just generated sum up

to 1 .

I am not sure how to do this. Any idea? Thanks.

numbers.append (random.uniform (0, 1.0-sum(numbers)))

might help, perhaps.

or

scaled = [x/sum(numbers) for x in numbers]

Mel.

Anthony Liu wrote:But, I want the random numbers just generated sum up

to 1 .

This seems like an odd request. Might I ask what it''s for?

Generating random numbers in [0,1) that are both uniform and sum to 1 looks

like an unsatisfiable task. Each number you generate restricts the

possibilities for future numbers. E.g. if the first number is 0.5, all

future numbers must be < 0.5 (indeed, must *sum* to 0.5). You''ll end up

with a distribution increasingly skewed towards smaller numbers the more

you generate. I can''t imagine what that would be useful for.

If that''s not a problem, do this: generate the numbers, add them up, and

divide each by the sum.

nums = [random.uniform(0,1) for x in range(0,100)]

sum = reduce(lambda x,y: x+y, nums)

norm = [x/sum for x in nums]

Of course now the numbers aren''t uniform over [0,1) anymore.

Also note that the sum of the normalized numbers will be very close to 1,

but slightly off due to representation issues. If that level of accuracy

matters, you might consider generating your rands as integers and then

fp-dividing by the sum (or just store them as integers/fractions).

Em S??b, 2006-04-22 ?*s 03:16 +0000, Edward Elliott escreveu:If that level of accuracy

matters, you might consider generating your rands as integers and then

fp-dividing by the sum (or just store them as integers/fractions).

Or using decimal module: http://docs.python.org/lib/module-decimal.html

--

Felipe.

最后

以上就是丰富灰狼为你收集整理的python生成和为1的随机数_生成一个总和为1的随机数序列?的全部内容,希望文章能够帮你解决python生成和为1的随机数_生成一个总和为1的随机数序列?所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部