In my basic multithreading exercises i use this unfortunate placeholder sub for simplification:
# this is still a fake! sub mandelbrot { int rand 20; }
But in reality i use a stolen solution (for the first).
For making this stuff my own (AKA understanding it) i tried to refactor it:
#!/usr/bin/env perl use strict; use warnings; use Imager; my $width = 320 * 10; my $height = 240 * 10; my $image = Imager->new( xsize => $width, ysize => $height ); my $black = Imager::Color->new( 0, 0, 0 ); my @palette; my $iterations = 20; for ( 1 .. $iterations ) { my ( $r, $g, $b ) = map { int rand 255 } 1 .. 3; push @palette, Imager::Color->new( $r, $g, $b ); } for my $x ( 0 .. $width - 1 ) { for my $y ( 0 .. $height - 1 ) { my $re_c = ( $x - 3 * $width / 4 ) / ( $width / 3 ); my $im_c = ( $y - $height / 2 ) / ( $width / 3 ); my ( $re_z, $im_z, $color, $test, $div ) = (0) x 5; while ( !$test ) { my $old_re_z = $re_z; $re_z = $re_z * $re_z - $im_z * $im_z + $re_c; $im_z = 2 * $old_re_z * $im_z + $im_c; ++$color; ( $test, $div ) = ( 1, 1 ) if $re_z * $re_z + $im_z * $im_z > 4; ( $test, $div ) = ( 1, 0 ) if $color == $iterations; } ($div) ? $image->setpixel( x => $x, y => $y, color => $palette[$col +or] ) : $image->setpixel( x => $x, y => $y, color => $black ); } } my $file = qq(mandelbrot.bmp); $image->write( file => $file );
I think this doesn't look so bad and it performs slightly better than the original.
But understanding the underlying algorithm isn't so easy for me.
So i thought renaming the names of some of the variables could make my life a bit easier, but I'm still struggling with some.
I wonder what would be "better" names for $test and $div. And doesn't $old_re_z look ugly?
Thank you very much for any hint.
Update: Perhaps a first presentable result:
Made with a little help of some friends ;-)
#!/usr/bin/env perl use strict; use warnings; use Imager; my $width = 1280; my $height = 1024; my $image = Imager->new( xsize => $width, ysize => $height ); my @palette = Imager::Color->new( 0, 0, 0 ); for ( 1 .. 20 ) { my ( $r, $g, $b ) = map { int rand 255 } 1 .. 3; push @palette, Imager::Color->new( $r, $g, $b ); } for my $x ( 0 .. $width - 1 ) { for my $y ( 0 .. $height - 1 ) { $image->setpixel( x => $x, y => $y, color => $palette[ mandelbrot( $x, $y ) ] ); } } my $file = qq(mandelbrot.bmp); $image->write( file => $file ); sub mandelbrot { my ( $x, $y ) = @_; my $re_c = ( $x - 3 * $width / 4 ) / ( $width / 3 ); my $im_c = ( $y - $height / 2 ) / ( $width / 3 ); my ( $re_z, $im_z, $iteration ) = (0) x 3; while (1) { my $temp = $re_z; $re_z = $re_z * $re_z - $im_z * $im_z + $re_c; $im_z = 2 * $temp * $im_z + $im_c; ++$iteration; last if $re_z * $re_z + $im_z * $im_z > 4; $iteration = 0, last if $iteration == 20; } return $iteration; } __END__
Best regards, Karl
«The Crux of the Biscuit is the Apostrophe»
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |