我需要生成3个随机浮点数(点后恰好有2位数),特定范围之间的特定平均值。
例如:
我希望平均值为37.14。我的最小值是31,而我的最大值是42。所以我想在这个范围内产生3个随机数,它给出了我想要的平均值:
41.35, 37.31, 32.77
我遇到了以下代码,但确实生成了整数。
n = 3;
xmean = 37;
xmin = 31;
xmax = 42;
xeps = 0.01;
x = randi([xmin xmax],n,1);
while abs(xmean - mean(x)) >= xeps
if xmean > mean(x)
x(find(x < xmean,1)) = randi([xmean xmax]);
elseif xmean < mean(x)
x(find(x > xmean,1)) = randi([xmin xmean]);
end
end
非常感谢任何帮助。
答案 0 :(得分:2)
只需将randi
替换为rand
:
n = 3;
xmean = 37;
xmin = 31;
xmax = 42;
xeps = 0.01;
x = 0.01*round(100*(xmin+(xmax-xmin)*rand(n,1)));
while abs(xmean - mean(x)) >= xeps
if xmean > mean(x)
x(find(x < xmean,1)) = 0.01*round(100*(xmean+(xmax-xmean)*rand(1)));
elseif xmean < mean(x)
x(find(x > xmean,1)) = 0.01*round(100*(xmin+(xmean-xmin)*rand(1)));
end
end
答案 1 :(得分:0)
另一个解决方案是将xmin xmean xmax乘以100.然后将结果除以100:
n = 3;
xmean = 37;
xmin = 31;
xmax = 42;
xeps = 0.01;
xmin = xmin*100;
xmax = xmax*100;
xmean = xmean*100;
x = randi([xmin xmax],n,1);
while abs(xmean - mean(x)) >= xeps
if xmean > mean(x)
x(find(x < xmean,1)) = randi([xmean xmax]);
elseif xmean < mean(x)
x(find(x > xmean,1)) = randi([xmin xmean]);
end
end
x = x .* 0.01
答案 2 :(得分:0)
考虑到约束,可以自由选择三个随机数中的两个。因此,您可以在范围内绘制两个数字并计算第三个数字。由于约束是均值,因此您知道至少有一个数字必须大于均值,并且必须小于均值才能减少迭代次数,直到找到满足范围的解决方案。
xmean = 37;
xmin = 31;
xmax = 42;
% scale for easier rounding to two digits
xmin = xmin*100;
xmax = xmax*100;
xmean = xmean*100;
foundSolution = false;
x = Nan(1,3);
while ~foundSolution
x(1) = randi([xmin,xmean]);
x(2) = randi([xmean,xmax]);
x(3) = 3*xmean-sum(x(1:2));
if x(3) >= xmin && x(3) <= xmax
foundSolution = true;
end
end
%# rescale back
x = x/100;