[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Under the microscope...



On Wed, 21 Jul 1999, Kevin Reid wrote:

> 
> BTW, anyone know how to generate the Mandelbrot set?
> 
Here's a quick and dirty. It's slower than it needs to be so that the
logic isn't obscured.

#!perl -w

# quickie program to demo Mandelbrot Set calculation.
# Calculates 0 or 1 value for each grid value within
# radius of 2. 

# numiter - number of iterations to see whether orbit
# diverges to infinity
# xinc, yinc - calculations are for each point in
#              -2.0 : 2.0 : $xinc for x
#              -2.0 : 2.0 : $yinc for y
# so these are the grid intervals

# The computation is of x^2 + c, where both x and c
# are complex (hence the 2-D grid). The seed value for
# x is (0.0, 0.0), or 0 + i0 if you wish, and c is
# ($x, $y), or $x + i $y. i is sqrt(-1). 

use POSIX;
use GD; 

$numiter = 20;
$xinc = 0.01;
$yinc = 0.01;
$xmax = POSIX::floor(2 / $xinc);
$ymax = POSIX::floor(2 / $yinc); 

$im = new GD::Image(2 * $xmax + 1,2 * $ymax + 1); 

$white = $im->colorAllocate(255,255,255);
$black = $im->colorAllocate(0,0,0);
@colors = ($white, $black); 

foreach $x (-$xmax..$xmax) {
	foreach $y (-$ymax..$ymax) {
		my @value = (0.0, 0.0); 
		my $ok = 1; 
		
		# do up to 'numiter' iterations. Set the pixel
		# to 0 (white) if the magnitude is > 2. 
		foreach my $i (1..$numiter) {
			@value = mset(@value, $x * $xinc, $y * $yinc); 
			if (sqmag(@value) > 4.0) { $ok = 0; last; }
		}
		$im->setPixel($x + $xmax, $y + $ymax, $colors[$ok]); 
	} }

open(MSET, ">mandel1.gif") or die;
binmode MSET; # Windows only
print MSET $im->gif;
close MSET; 

sub mset {
	my ($nr, $nc, $cr, $cc) = @_; 
	
	($nr * $nr - $nc * $nc + $cr, 2.0 * $nr * $nc + $cc);  }

sub sqmag {
	my ($real, $cplx) = @_; 
	
	$real * $real + $cplx * $cplx;  }



===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org