成功之后,我编写了以下代码,基于for循环使用蒙特卡罗方法近似数字pi:
function piapprox = calcPiMC(n)
count = 0; % count variable, start value set to zero
for i=1:n; % for loop initialized at one
x=rand; % rand variable within [0,1]
y=rand;
if (x^2+y^2 <=1) % if clause, determines if pair is within the first quadrant of the unit circle
count = count +1; % if yes, it increases the count by one
end
end
piapprox = 4*(count/n);
end
这种方法很棒但是对于大n
的大值开始挣扎很多。作为我自己的一项任务,我想尝试对以下代码进行矢量化,不使用使用任何循环等。在我脑海中,我可以想到一些对我来说有意义的伪代码,但到目前为止我无法完成它。这是我的方法:
function piapprox = calcPiMCVec(n)
count = zeros(size(n)); % creating a count vector filled with zeros
x = rand(size(n)); % a random vector of length n
y = rand(size(n)); % another random vector of length n
if (x.*x + y.*y <= ones(size(n))) % element wise multiplication (!!!)
count = count+1; % definitely wrong but clueless here
end
piapprox=4*(count./n);
end
我希望在阅读这个伪代码时我的想法看起来很清楚,但我会对它们发表评论。
n
x
和y
cumsum
函数,但是结果出错了答案 0 :(得分:4)
这是一个矢量化解决方案,其中包含一系列评论,部分参考了您的尝试。
function piapprox = calcPiM(n)
%#CALCPIM calculates pi by Monte-Carlo simulation
%# start a function with at least a H1-line, even better: explain fcn, input, and output
%# start with some input checking
if nargin < 1 || isempty(n) || ~isscalar(n)
error('please supply a scalar n to calcPiM')
end
%# create n pairs of x/y coordinates, i.e. a n-by-2 array
%# rand(size(n)) is a single random variable, since size(n) is [1 1]
xy = rand(n,2);
%# first, do element-wise squaring of array, then sum x and y (sum(xy.^2,2))
%# second, count all the radii smaller/equal 1
count = sum( sum( xy.^2, 2) <= 1);
%# no need for array-divide here, since both count and n are scalar
piapprox = 4*count/n;