julia_set.jl 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/julia
  2. # Trizen
  3. # 27 March 2016
  4. # https://github.com/trizen
  5. # Generate a random Julia set as a PNG image.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Julia_set
  8. using Images
  9. @inline function hsv2rgb(h, s, v)
  10. c = v * s
  11. x = c * (1 - abs(((h/60) % 2) - 1))
  12. m = v - c
  13. if h < 60
  14. r,g,b = (c, x, 0)
  15. elseif h < 120
  16. r,g,b = (x, c, 0)
  17. elseif h < 180
  18. r,g,b = (0, c, x)
  19. elseif h < 240
  20. r,g,b = (0, x, c)
  21. elseif h < 300
  22. r,g,b = (x, 0, c)
  23. else
  24. r,g,b = (c, 0, x)
  25. end
  26. (r + m), (b + m), (g + m)
  27. end
  28. function julia_set()
  29. w, h = 1000, 1000
  30. zoom = 0.5 # the zoom factor
  31. moveX = 0 # the amount of shift on the x axis
  32. moveY = 0 # the amount of shift on the y axis
  33. L = 2 # the maximum value of |z|
  34. I = 30 # the maximum number of iterations
  35. img = zeros(RGB{Float64}, h, w)
  36. c = Complex(-rand(), 2 * rand() * (rand() < 0.5 ? 1 : -1))
  37. for x in 1:w, y in 1:h
  38. n = 0
  39. z = Complex(
  40. (2*x - w) / (w * zoom) + moveX,
  41. (2*y - h) / (h * zoom) + moveY
  42. )
  43. while abs(z) < L && (n += 1) < I
  44. z = z^2 + c
  45. end
  46. v = (I - n) / I
  47. r,g,b = hsv2rgb(v*360, 1, v)
  48. img[y,x] = RGB{Float64}(r, g, b)
  49. end
  50. println("Generating image...")
  51. save("$c-$zoom.png", img)
  52. end
  53. julia_set()