開発環境
- 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)の Exercise 6-1.を取り組んでみる。
Exercise 6-1.
コード(Emacs)
#!/usr/bin/env perl6
# -*- coding: utf-8 -*-
sub my-sqrt($a) {
my $x = 1;
while True {
my $y = ($x + $a / $x) / 2;
last if $y == $x;
$x = $y;
}
return $x;
}
say 'a mysqrt(a) sqrt(a) diff';
for 1..9 {
my $a = my-sqrt($_);
my $b = sqrt($_);
my $diff = abs($a - $b);
say "$_ $a $b $diff";
}
入出力結果(Terminal, REPL)
$ ./sample1.pl 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 $
0 コメント:
コメントを投稿