Why is incorrect value of pi output?

点点圈 提交于 2021-01-28 07:50:29

问题


I'm trying to calculate pi using following code that uses Chudnovsky algorithm. When $n is increased, then number of digits after the decimal point. However when $n is small, it can calculate correct value of pi (3.141592...) is output, but when $n is increased, it calculate incorrect value of pi. Why?

#!/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;
}

来源:https://stackoverflow.com/questions/55801898/why-is-incorrect-value-of-pi-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!