Fractals are complex patterns that are self-similar across different scales. They are fascinating both in their mathematical properties and their visual appeal. In this chapter, we will explore how to program fractals using Elixir, BQN, and Haskell, focusing on some of the most famous fractal patterns such as the Mandelbrot set and the Sierpinski triangle.
=== The Mandelbrot Set
The Mandelbrot set is a set of complex numbers that produces a distinctive and famous fractal shape. The set is defined by iterating the function:
[stem]
++++
z_{n+1} = z_n^2 + c
++++
==== Plotting the Mandelbrot Set in Elixir
Let's start with a basic Elixir program to plot the Mandelbrot set.
[source,elixir]
----
defmodule Mandelbrot do
def mandelbrot(c, max_iter) do
iterate(c, 0, 0, max_iter)
end
defp iterate(_c, _z, n, max_iter) when n >= max_iter, do: n
defp iterate(c, z, n, max_iter) when abs(z) > 2, do: n
defp iterate(c, z, n, max_iter) do
iterate(c, z*z + c, n + 1, max_iter)
end
def mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iter) do
Julia sets are another type of fractal, closely related to the Mandelbrot set. They are generated using a similar iterative function but with a fixed complex parameter.
==== Plotting a Julia Set in Elixir
Here's an Elixir program to plot a Julia set.
[source,elixir]
----
defmodule Julia do
def julia(c, z, max_iter) do
iterate(c, z, 0, max_iter)
end
defp iterate(_c, _z, n, max_iter) when n >= max_iter, do: n
defp iterate(c, z, n, max_iter) when abs(z) > 2, do: n
defp iterate(c, z, n, max_iter) do
iterate(c, z*z + c, n + 1, max_iter)
end
def julia_set(c, xmin, xmax, ymin, ymax, width, height, max_iter) do
Fractals are an excellent way to understand the beauty and complexity of mathematical patterns. By programming these patterns, we not only appreciate their aesthetic appeal but also gain insights into their mathematical properties.
=== Further Reading
For more information on fractals and programming, check out the following resources:
* https://en.wikipedia.org/wiki/Mandelbrot_set[Mandelbrot Set - Wikipedia]