mandelbrot.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. -- Mandelbrot benchmark from benchmarks game
  2. -- https://benchmarksgame-team.pages.debian.net/benchmarksgame/description/mandelbrot.html
  3. --
  4. -- Translated from the Java version found at
  5. -- https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/mandelbrot-java-1.html
  6. --
  7. -- * I don't use any explicit buffering. In my experiments it speeds up the
  8. -- program by less than 10%, while considerably increasing the complexity.
  9. -- * The LuaJIT version needs to be separate, due to the lack of bitwise ops.
  10. -- * The output is in the Netpbm file format. Use an image viewer to view the picture.
  11. local function mandelbrot(N)
  12. local bits = 0
  13. local nbits = 0
  14. local delta = 2.0 / N
  15. for y = 0, N-1 do
  16. local Ci = y*delta - 1.0
  17. for x = 0, N-1 do
  18. local Cr = x*delta - 1.5
  19. local bit = 0x1
  20. local Zr = 0.0
  21. local Zi = 0.0
  22. local Zr2 = 0.0
  23. local Zi2 = 0.0
  24. for _ = 1, 50 do
  25. Zi = 2.0 * Zr * Zi + Ci
  26. Zr = Zr2 - Zi2 + Cr
  27. Zi2 = Zi * Zi
  28. Zr2 = Zr * Zr
  29. if Zi2 + Zr2 > 4.0 then
  30. bit = 0x0
  31. break
  32. end
  33. end
  34. bits = (bits << 1) | bit
  35. nbits = nbits + 1
  36. if nbits == 8 then
  37. io.write(string.char(bits))
  38. bits = 0
  39. nbits = 0
  40. end
  41. end
  42. if nbits > 0 then
  43. bits = bits << (8 - nbits)
  44. io.write(string.char(bits))
  45. bits = 0
  46. nbits = 0
  47. end
  48. end
  49. end
  50. return function(N)
  51. N = N or 100
  52. io.write(string.format("P4\n%d %d\n", N, N))
  53. mandelbrot(N)
  54. end