Monte Carlo pi计算能否用于世界纪录? [英] Can a Monte Carlo pi calculation be used for a world record?

查看:170
本文介绍了Monte Carlo pi计算能否用于世界纪录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个随机函数来计算pi ?如果是这样,我怎么才能找到将提供第N位数的迭代次数?

解决方案

这是计算丕,但它可能是一个非常低效的。一些说法:


  • 在我喝咖啡之前,我的统计数字已经生锈了,但是我猜这个错误是根据 1 / sqrt(n_guess)。为了得到N位数,你需要一个 10 ^( - N)的错误,所以你需要大概(10 ^ N)^ 2 随机猜测。如果你想按照你的建议进行1e100的猜测,你只能得到50位数字的pi!因此迭代的次数是所需位数的一些指数函数,这是非常慢的。一个好的算法可能是你想要的位数的线性。

  • 随着大量的猜测,你必须开始质疑你的随机性数字发生器。

  • 您的算法将被浮点错误限制为1e-16左右。计算pi的数字需要某种精确的数字格式。

  • 为了加快你的算法,你可以省略sqrt()。不要使用名为 max 的变量,这会覆盖现有的函数。 使用n_guess左右。




快速和肮脏的测试证明我的理论(咖啡后):$ (n(n,1))^ 2 + rand(n,1)。^ 2 $ b

  1)/ n; 
ntrial = round(logspace(1,8,100));
pies = arrayfun(pie,ntrial);
$ b $ loglog(ntrial,abs(pies-pi),'.k',ntrial,ntrial。^ - 。5,' - r')
xlabel('ntrials')$ ('Monte Carlo','1 / sqrt(ntrial)')


I have this random function to calculate pi Monte Carlo style:

max=10000000;
format long;

in = 0;
tic
for k=1:max
    x = rand();
    y = rand();
    if sqrt(x^2 + y^2) < 1
        in = in + 1;
    end
end

toc
calc_pi = 4*in/max 
epsilon = abs(pi - calc_pi)

calcPi(100000000);

If I could iterate this 10e100 times, could this algorithm compete with the world record? If so, how can I find the number of iteration that will give the Nth digit?

解决方案

This is a nice exercise for calculating pi, but it is probably a very inefficient one. Some remarks:

  • My statistics are rusty before I had my coffee, but I guess the error scales with 1 / sqrt(n_guess). To get N digits, you need an error of 10^(-N), so you would need roughly (10^N)^2 random guesses. If you would do 1e100 guesses, as you proposed, you would only get on the order of 50 digits of pi! The number of iteration is thus some exponentional function of the number of required digits, which is horribly slow. A good algorithm is maybe linear in the number of digits you want.

  • With the large number of guesses required, you have to start questioning the quality of your random number generator.

  • Your algorithm will be limited by floating-point errors to 1e-16 or so. Calculating digits of pi requires some sort of arbitrary precision number format.

  • To speed up your algorithm, you can leave out the sqrt().

  • Don't use a variable called max, this overwrites an existing function. Use n_guess or so.

Quick and dirty test to prove my theory (after coffee):

pie = @(n) 4 * nnz(rand(n,1).^2 + rand(n, 1).^2 < 1) / n;
ntrial = round(logspace(1, 8, 100));
pies = arrayfun(pie, ntrial);

loglog(ntrial, abs(pies - pi), '.k', ntrial, ntrial.^-.5, '--r')
xlabel('ntrials')
ylabel('epsilon')
legend('Monte Carlo', '1 / sqrt(ntrial)')

这篇关于Monte Carlo pi计算能否用于世界纪录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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