開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Perl 6 (プログラミング言語)
- Rakudo(コンパイラ、実装)
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)の Exercises 6-1、6-2.を取り組んでみる。
Exercises 6-1、6-2.
コード(Emacs)
#!/usr/bin/env perl6
# -*- coding: utf-8 -*-
say '1.';
sub my-sqrt($a) {
my $x = 1;
while True {
my $y = ($x + $a / $x) / 2;
last if $y == $x;
$x = $y;
}
$x;
}
sub test-sqaure-root {
say 'a mysqrt(a) sqrt(a) diff';
for 1..10 {
my $x = my-sqrt($_);
my $y = sqrt($_);
say "$_ $x $y ", abs $x - $y;
}
}
test-sqaure-root();
say '2.';
sub factorial($n) {
return 1 if $n <= 1;
$n * factorial($n - 1);
}
sub estimate-pi() {
my $epsilon = 1e-15;
my $sum = 0;
my $k = 0;
while True {
my $term = factorial(4 * $k) * (1103 + 26390 * $k) /
(factorial($k) ** 4 * 396 ** (4 * $k));
$sum += $term;
last if $term < $epsilon;
$k += 1;
}
1 / (2 * sqrt(2) / 9801 * $sum);
}
say 'estimate-pi pi diff';
my $pi = estimate-pi;
say "$pi ", pi, ' ', abs $pi - pi;
入出力結果(Terminal, REPL)
$ ./sample1.pl 1. a mysqrt(a) sqrt(a) diff 1 1 1 0 2 1.41421356237309 1.4142135623731 2.22044604925031e-16 3 1.7320508075688772935 1.73205080756888 0 4 2 2 0 5 2.236067977499790 2.23606797749979 0 6 2.44948974278318 2.44948974278318 0 7 2.64575131106459 2.64575131106459 0 8 2.82842712474619 2.82842712474619 4.44089209850063e-16 9 3.00000000000000000033 3 0 10 3.16227766016838 3.16227766016838 4.44089209850063e-16 2. estimate-pi pi diff 3.14159265358979 3.14159265358979 0 $
0 コメント:
コメントを投稿