Saturday, June 13, 2009

Mandelbrot in Perl 6

I decided to take a stab at translating mandel.pl from The Computer Language Benchmarks Game to Perl 6. I got rid of the threading, and because I was unable to get pack working (not there or just 5 AM programming issues?), I switched it from a P4 binary file to a P1 ASCII file. The resulting code runs in 3 minutes and 20 seconds, where the unthreaded version of the original runs in 0.2 seconds, so there is a lot of room for improvement here.

# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
# implemented by Greg Buchholz
# streamlined by Kalev Soikonen
# parallelised by Philip Boulain
# modified by Jerry D. Hedden
# translated to Perl 6 by SF
use v6;
constant ITER = 50;
constant LIMITSQR = 2.0 ** 2;
my ($w, $h);
$w = $h = shift @*ARGS || 80;
# Generate pixel data for a single dot
sub dot($x, $y)
{
my ($Zr, $Zi, $Tr, $Ti) = (0.0,0.0,0.0,0.0);
my $i = ITER;
my $Cr = 2 * $x / $w - 1.5;
my $Ci = 2 * $y / $h - 1.0;
while $Tr + $Ti < LIMITSQR && $i--
{
$Zi = 2.0 * $Zr * $Zi + $Ci;
$Zr = $Tr - $Ti + $Cr;
$Ti = $Zi * $Zi;
$Tr = $Zr * $Zr;
}
return $i == -1;
}
# Generate pixel data for range of lines, inclusive
sub lines(Num $low_y, Num $high_y)
{
for $low_y..$high_y -> $y
{
say join ' ', map { dot($_, $y) }, 0..$w-1;
}
}
print "P1\n$w $h\n";
lines(0, $h);
view raw mandel.pl hosted with ❤ by GitHub


I'll probably also take a stab at revamping the dot function to use the Complex type, assuming it actually is implemented, and maybe making lines feel more Perl 6ish.

No comments:

Post a Comment