如何使用Ramanujan的融合系列在MATLAB中生成数百个pi数字?

时间:2014-05-19 21:33:17

标签: matlab digits pi

我正在尝试使用Ramanujan的融合系列: http://en.wikipedia.org/wiki/Approximations_of_%CF%80#20th_century

我使用数字()和vpa()来提高每个术语的精确度,如我的代码所示。

num_digits = 20000;
digits(num_digits+1)
ram_pi_init = vpa(0);
t1 = vpa(2);
t2 = vpa(sqrt(2));
t3 = vpa(1/9801);
for k=0:8
    t4 = vpa(factorial(4*k)); %INF after k=42
    if t4 == Inf
        t4=1;
        for kk = 1:4*k
            t4 = vpa(t4*kk);
        end
    end
    t5 = vpa(1103+26390*k);
    t6_temp = vpa(factorial(k));
    if t6_temp == Inf
        t6_temp=1;
        for kk = 1:k
            t6_temp = vpa(t6_temp*kk);
        end
    end
    t6 = vpa(1/t6_temp^4);
    %t7 = vpa(1/396^(4*k)); Does not work properly
    t7=vpa(1);
    for kk = 1:4*k
        t7 = vpa(t7/396);
    end
    increment = vpa(t1*t2*t3*t4*t5*t6*t7);
    ram_pi_init = vpa(ram_pi_init + increment);
end
ram_pi_sym = vpa(1/ram_pi_init);
ram_pi_str = char(ram_pi_sym);
ram_pi = [];
for i = 3:num_digits+1
    ram_pi(i-2) = str2num(ram_pi_str(i));
end

%% compare
correct_streak = 0;
for i = 1:num_digits
    if pi(i) == ram_pi(i)
        fprintf('Y\n')
        correct_streak = correct_streak + 1;
    else
        break
    end
end

1 个答案:

答案 0 :(得分:0)

假设k很大(250+)。仔细看看你如何使用factorialfactorial(k)inf,inf的vpa表示仍为inf:vpa(factorial(k))。相反,您必须先转换为VPA,然后使用factorial:factorial(vpa(k))

vpa(1/396^(4*k))相同,您的结果为inf,然后转换为vpa。 vpa(1/396)^(4*k)应该没问题。