为什么pi输出值不正确?

时间:2019-04-22 22:28:46

标签: perl gmp pi

我正在尝试使用以下使用Chudnovsky算法的代码来计算pi。 $ n增加时,小数点后的位数。但是,当$ n小时,可以计算出正确的pi值(3.141592 ...),但是当$ n增加时,它可以计算出不正确的pi值。为什么?

#!/usr/bin/perl

use strict;
use warnings;
use GMP qw(:all);
use GMP::Mpf qw(:all);
use GMP::Mpz qw(:all);
use GMP::Mpq qw(:all);

my $n = shift; $n = $n<7?7:$n;
$n *= 8;
my $l = int($n/7) + 1;

my $fmt = '%.' . $n . 'f';

my ($p0, $q0, $t0) = (1, 1, 0);

$p0 = mpz($p0);
$q0 = mpz($q0);
$t0 = mpz($t0);

my ($p, $q, $t, $a) = (0, 0, 0, 0);

$p = mpz($p);
$q = mpz($q);
$t = mpz($t);
$t = mpz($a);

for my $loop (1 .. $l){
    $p = (2*$loop -1)*(6*$loop -1)*(6*$loop -5);
    $q = ($loop**3)*(640320**3)/24;
    $a = (-1)**$loop + (13591409 + 545140134*$loop);
    $p *= $p0;
    $q *= $q0;
    $t = $t0*$p + $a*$p;

    $p0 = $p;
    $q0 = $q;
    $t0 = $t;
}

my $x = sr(640320,$n);
$q = mpf($q,$n);
$t = mpf($t,$n);

my $pi = mpf(640320,$n)*sr(mpf(640320,$n),$n)*$q;
$pi /= mpf(12,$n)*($t + mpf(13591409,$n)*$q);

print $pi . "\n";

sub sr{
    my ($x,$i) = @_;

    my $s = mpf(0.0,$i);
    my $s0 = mpf($x,$i);

    for (1 .. $n){
        $s = 1/$s0;
        $s *= $x;
        $s0 = ($s + $s0)/mpf(2.0,$i);
    }
    return $s;
}

0 个答案:

没有答案