2017年4月8日土曜日

開発環境

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

Exercise 6-2.

コード(Emacs)

#!/usr/bin/env perl6
# -*- coding: utf-8 -*-

sub factorial($n) {
    return 1 if $n <= 1;
    $n * factorial($n - 1);
}

sub term($k) {
    my $num = factorial(4 * $k) * (1103 + 26390 * $k);
    my $den = factorial($k) ** 4 * 396 ** (4 * $k);
    return  $num / $den;
           
}

sub estimate-pi {
    my $result = 0;
    my $k = 0;
    my $term = term($k);
    while ($term >= 1e-15) {
        $result += $term;
        $k += 1;
        $term = term($k);
    }
    return 1 / (2 * sqrt(2) / 9801 * $result);
}

say "estimate-pi: ", estimate-pi;
say "built-in constant pi: ", pi;
say "difference: ", abs(estimate-pi() - pi);

入出力結果(Terminal, REPL)

$ ./sample2.pl
estimate-pi: 3.14159265358979
built-in constant pi: 3.14159265358979
difference: 0
$

0 コメント:

コメントを投稿