Skip to content

Instantly share code, notes, and snippets.

@halirutan
Created September 5, 2017 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halirutan/7b58829721f58bff470521cb9a1cdb0e to your computer and use it in GitHub Desktop.
Save halirutan/7b58829721f58bff470521cb9a1cdb0e to your computer and use it in GitHub Desktop.
Naive implementation of visualizing a julia set with Kotlin
package de.halirutan.kotlin
import java.awt.Color
import java.awt.Image
import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
val log2 = Math.log(2.0)
data class Triple(private val a: Double, private val b: Double, private val c: Double) {
fun toRGB() : Int {
return Color.HSBtoRGB(a.toFloat(), b.toFloat(), c.toFloat())
}
}
data class Complex(private val re: Double, private val im: Double) {
operator fun plus(z: Complex) = Complex(re+z.re, im+z.im)
operator fun times(z: Complex) = Complex(re*z.re-im*z.im, re*z.im+im*z.re)
fun abs() = Math.sqrt(re*re+im+im)
override fun toString() = "$re+I*$im"
}
fun iterator(juliaFunction: (Complex) -> Complex, zStart: Complex, maxIter: Int): Triple {
var z = zStart
for (i in 0..maxIter) {
if (z.abs() > 2.0) {
return Triple(0.0, 0.0, (i.toDouble())/maxIter.toDouble() + (log2/z.abs())/5.0)
}
z = juliaFunction(z)
}
return Triple(Math.cos(1 - (log2/z.abs())+Math.PI/2.0), 1.0, 1.0)
}
fun createJuliaImage(nx: Int, ny: Int, juliaFunction: (Complex) -> Complex) : Image {
val data = Array(nx*ny, {
val x = 2.0*(it % nx)/nx.toDouble() - 1.0
val y = 2.0*(it / nx)/ny.toDouble() -1.0
Complex(x,y)
})
val pixel = data.map({iterator(juliaFunction,it, 200).toRGB()})
val img = BufferedImage(nx, ny, BufferedImage.TYPE_INT_RGB)
img.setRGB(0, 0, nx, ny, pixel.toIntArray(), 0, nx)
return img
}
fun main(args: Array<String>) {
val nx = 2048
val ny = 2048
val f: (Complex) -> Complex = {z -> z*z+Complex(-0.8, 0.156)}
val img = createJuliaImage(nx, ny, f)
val scaledImg = img.getScaledInstance(nx/2, ny/2, Image.SCALE_SMOOTH)
val frame = JFrame("Julia Image")
val imgAsLabel = JLabel()
imgAsLabel.icon = ImageIcon(scaledImg)
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
val panel = JPanel()
panel.add(imgAsLabel)
frame.contentPane.add(panel)
frame.pack()
frame.isVisible = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment