P is for Practical | |
PerlMonks |
Plot Pretty Fractals with Perlby tsee (Curate) |
on Aug 29, 2003 at 18:39 UTC ( [id://287793]=CUFP: print w/replies, xml ) | Need Help?? |
This is a short introduction to one of the CPAN modules dealing with fractals. According to the Merriam-Webster dictionary, a fractal is "any of various extremely irregular curves or shapes for which any suitably chosen part is similar in shape to a given larger or smaller part when magnified or reduced to the same size." While that's pretty hard to parse for my head, I think I can safely assume that most readers have seen one of the more famous fractals like the von-Koch Curve before. Hence I will not go into details on fractals or even the underlying mathematics. I suggest you have a look at the documents in the references section below. Introducing Math::Fractal::CurveThe Math::Fractal::Curve module from CPAN may be used to recursively calculate fractal curves from simple generator datastructures to arbitrary precisions. These generators specify a number of distances in two dimensions and relative to the distance from (0,0) to (1,0). Math::Fractal::Curve calculates fractals by repeatedly replacing all distances in the fractal with a scaled and rotated version of the distances specified by the generator. Getting the feet wetLet's start writing some code that demonstrates basic usage.
As you can see in the above example, generators in their simplest form are syntactically no more than nested array references and a few numbers. The example specifies four distances (the four inner array references) that will be used to replace any distance. The numbers are relative to the length of the replaced distance and have the same orientation.
Great, so what? -or- Imager to the rescueNow we have a large array of array refs that each hold four numbers. That did not take us much closer to the pretty picture I gave as an example above. We'll need some drawing to realize that. Luckily, Arnar Mar Hrafnkelsson wrote the excellent Imager module to do the hard work!
No deep thinking required to understand the above code. We scale the distances to be large enough to be drawn conveniently. The call to Imager's line() method may look more complicated than it really is. All the maths is just moving the fractal to the center of the image. More'o'That
The above example demonstrates the bare minimum needed to get started
with letting your computer plot some fractals, but it has a few limitations
and does not demonstrate the full power of the module. References
MathWorld
Back to
Cool Uses for Perl
|
|