Created
March 13, 2026 15:49
-
-
Save synapticvoid/2458dd45c735bfd51d0601199da3d2b1 to your computer and use it in GitHub Desktop.
Basic implementation of the Mandelbrot fractal in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.awt.image.BufferedImage | |
| data class FractalParams( | |
| val width: Int, | |
| val height: Int, | |
| val maxIterations: Int = 256, | |
| ) | |
| fun render(params: FractalParams): BufferedImage { | |
| val image = BufferedImage(params.width, params.height, BufferedImage.TYPE_INT_RGB) | |
| for (py in 0 until params.height) { | |
| for (px in 0 until params.width) { | |
| // Map pixel coordinates to the complex plane [-2, 2] | |
| val cx = (px - params.width / 2.0) / (params.width / 4.0) - 0.5 | |
| val cy = (py - params.height / 2.0) / (params.height / 4.0) | |
| val iterations = iterate(cx, cy, params.maxIterations) | |
| // Black = inside the set, white = outside | |
| val color = if (iterations == params.maxIterations) 0x000000 else 0xFFFFFF | |
| image.setRGB(px, py, color) | |
| } | |
| } | |
| return image | |
| } | |
| // Returns the number of iterations before the sequence escapes, | |
| // or maxIterations if it never does (point is in the Mandelbrot set). | |
| fun iterate(cx: Double, cy: Double, maxIterations: Int): Int { | |
| var zx = 0.0 | |
| var zy = 0.0 | |
| var i = 0 | |
| // The sequence z_{n+1} = z_n^2 + c diverges when |z| >= 2 (i.e. |z|^2 >= 4) | |
| while (i < maxIterations && zx * zx + zy * zy < 4.0) { | |
| val newZx = zx * zx - zy * zy + cx // Re(z^2 + c) | |
| zy = 2.0 * zx * zy + cy // Im(z^2 + c) | |
| zx = newZx | |
| i++ | |
| } | |
| return i | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment