我想在MATLAB中创建一个计算R^n中的n球体积的函数。为此,我使用Monte-Carlo方法在n立方体中随机生成点,然后使用n球内的点与所有生成点相乘的比率乘以n立方体的体积。这里是我迄今为止产生的代码:使用Monte-Carlo方法计算n球的体积
function [ approximate_volume ] = MonteCarloHypersphereVolume(radius, dimension, number_of_generations)
%MonteCarloHypersphereVolume Computes the volume of a
%'dimension'-dimensional hypersphere by the Monte Carlo method
number_within_sphere = 0;
parfor i = 1 : number_of_generations
randoms = zeros(1, dimension);
for j = 1 : dimension
randoms(j) = randi(radius * 2) - radius;
end
if sum(randoms .^ 2) <= radius^2
number_within_sphere = number_within_sphere + 1;
end
end
approximate_volume = (number_within_sphere/number_of_generations) * (2*radius)^dimension;
end
但是,这看起来是非常不准确的;根据维基百科,单位10球的数量应该是:V_10 = pi^5/5! = 2.5502,但是当运行1000000次迭代的函数时,它返回11.0067,确实多次运行它总是返回一个大约为11的值,这比它应该高得多?
此外,有没有办法使用GPGPU编程来提高此功能的性能?除了number_within_sphere
的数据依赖性外,它似乎很容易并行化?
我可以使用R来验证一般的方法应该工作。你使用了什么“半径”?你知道['randi'](http://www.mathworks.de/de/help/matlab/ref/randi.html)返回*整数*吗?你可能更喜欢['rand'](http://www.mathworks.de/de/help/matlab/ref/rand.html),你可以对它进行矢量化处理以放弃你的'for'循环。 – MvG
你的循环也不需要依赖'radius'。 'number_within_sphere'可以计算一个单位的n球。不要问两个单独的问题是个好主意。 – horchler