为什么这发生在随机矩阵中,使得所有行的总和为1? [英] Why this thing happens with random matrix such that all rows sum up to 1?

查看:160
本文介绍了为什么这发生在随机矩阵中,使得所有行的总和为1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个随机矩阵,其行总和为1.我找到了这个问题,并回答了如何创建一个随机矩阵,使所有行的总和为1 ,这正是我想要的.

I would like to generate a random matrix whose rows sum up to one. I found this question and answers How to create a random matrix such that all rows sum to 1 which do what I exactly want.

问题是当我这样做时,有时总和并不完全是一个.

The problem is when I did it, sometimes the sum is not exactly one.

mat      = rand(2, 2);
rowsum   = sum(mat, 2);
mat      = bsxfun(@rdivide, mat, rowsum);

有时候我会得到这样的东西:

Sometimes I get something like this:

sum_test = sum(mat, 2)-1
1.0e-15 *
      0
-0.2220;

我不知道为什么?

推荐答案

Matlab使用双精度数字,这意味着只能表示有限的一组数字.可以使用eps函数在Matlab中找到双精度数之间的间隔.对于值1,这几乎是您对每一行求和时得到的值eps(1) = 2.220446049250313e-16,这与您得到的幅度数值误差相同.当您将矩阵中的每个值相除时会引入该错误.有关Matlab精度的详细信息,请此处.

Matlab uses double-precision numbers, which means there are only a finite set of numbers that can be represented. The gap between double-precision numbers can be found in Matlab using the eps function. For a value of 1, which is pretty much the value you get when you sum up each row, eps(1) = 2.220446049250313e-16, which is the same magnitude numerical error you're getting. The error is introduced when you divide each value in the matrix. More information about Matlab precision here.

即使像从每行的第一个值中减去错误之类的方法也不能完全解决您的问题(尽管确实有帮助).例如

Even doing something like subtracting the error from the first value in each row doesn't solve your problem completely (although it does help). For example,

mat = rand(10,10);
rowsum = sum(mat,2);
mat = bsxfun(@rdivide,mat,rowsum);
sum_test = sum(mat,2)-1    %finite error
mat(:,1) = mat(:,1) - sum_test; %subtract the error from the first column in each row
sum_test2 = sum(mat,2)-1   %still get error

结果

sum_test = [
-1.110223024625157e-16
                     0
                     0
                     0
                     0
-2.220446049250313e-16
                     0
-2.220446049250313e-16
-1.110223024625157e-16
-2.220446049250313e-16]

sum_test2 = [
 2.220446049250313e-16
                     0
                     0
                     0
                     0
                     0
                     0
                     0
-1.110223024625157e-16
                     0]

(您可以证明,即使(sum(mat,2)-0.5)-0.5给出的答案也不同于sum(mat,2)-1)

(You can show that even (sum(mat,2)-0.5)-0.5 gives a different answer than sum(mat,2)-1)

这篇关于为什么这发生在随机矩阵中,使得所有行的总和为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆