2017年2月25日土曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のChapter 6(Iteration)のExercises 6-1、2.を取り組んでみる。

Exercises 6-1、2.

コード(Emacs)

#!/usr/bin/env perl6

say '6-1.';

sub my-sqrt($a) {
    my $epsilon = 0.0000001;
    my $x = 1;

    $x = ($x + $a / $x) / 2 while abs($x - $a / $x) > $epsilon;

    $x;
}

say 'a mysqrt(a) sqrt(a) diff';
for 1..9 {
    my $x = my-sqrt $_;
    my $y = sqrt $_;
    my $d = abs($x - $y);
    say "$_ $x $y $d";
}


say '6-2.';

sub fact($n) {
    return 1 if $n < 2;
    $n * fact($n - 1);
}
sub term($k) {
    fact(4 * $k) * (1103 + 26390 * $k) / (fact($k) ** 4 * 396 ** (4 * $k));    
}
sub my-pi {
    my $epsilon = 1e-15;

    my $k = 0;
    my $t = term($k);
    my $result = $t;

    while $t >= $epsilon {
        $k++;
        $t = term($k);
        $result += $t;
    }

    9801 / (2 * (sqrt 2) * $result);
}

say 'my-pi pi diff';
say my-pi() , ' ', pi, ' ', abs(my-pi() - pi);

入出力結果(Terminal)

$ ./sample1.pl
6-1.
a mysqrt(a) sqrt(a) diff
1 1 1 0
2 1.4142136 1.4142135623731 1.59472435257157e-12
3 1.732051 1.73205080756888 2.44585041109247e-09
4 2.0000000000000022 2 2.22044604925031e-15
5 2.23606798 2.23606797749979 1.88293824976427e-13
6 2.449489742787551656 2.44948974278318 4.37383462781327e-12
7 2.64575131111137 2.64575131106459 4.67785810087662e-11
8 2.8284271250498641300 2.82842712474619 3.03673974855201e-10
9 3.00000000140 3 1.39698386192322e-09
6-2.
my-pi pi diff
3.14159265358979 3.14159265358979 0
$

0 コメント:

コメントを投稿

Comments on Google+: