-
Notifications
You must be signed in to change notification settings - Fork 33
/
farey_turnings_plot.pl
executable file
·64 lines (45 loc) · 1.08 KB
/
farey_turnings_plot.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/perl
# Plot the turnings in the Farey approximation process.
# See also:
# https://en.wikipedia.org/wiki/Farey_sequence
# https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree
use 5.020;
use strict;
use warnings;
use GD::Simple;
use Math::AnyNum qw(abs);
use experimental qw(signatures);
sub farey_approximation ($r) {
my ($m, $n) = abs($r)->rat_approx->nude;
my $enc = '';
for (; ;) {
if ((($m <=> $n) || last) < 0) {
$enc .= '0';
$n -= $m;
}
else {
$enc .= '1';
$m -= $n;
}
}
return $enc;
}
my $turns = do {
local $Math::AnyNum::PREC = 30000;
farey_approximation(Math::AnyNum::tau());
};
say substr($turns, 0, 50);
my $width = 2000;
my $height = 2000;
my $img = 'GD::Simple'->new($width, $height);
$img->moveTo($width / 1.75, $height / 1.25);
my $angle = 60;
foreach my $t (split(//, $turns)) {
$t
? $img->turn($angle)
: $img->turn(-$angle);
$img->line(5);
}
open my $fh, '>:raw', 'farey_plot.png' or die $!;
print {$fh} $img->png;
close $fh;