mandelbrot.sh 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. BAILOUT=16
  4. MAX_ITERATIONS=1000
  5. function iterate {
  6. # $1 is x
  7. # $2 is y
  8. local zi=0
  9. local zr=0
  10. local i=0
  11. local cr
  12. cr=$(printf "%s\n" "scale=16; $2 - 0.5" | bc)
  13. while true
  14. do
  15. local temp
  16. local zr2
  17. local zi2
  18. i=$((i + 1))
  19. zr2=$(printf "%s\n" "scale=16; ($zr * $zr) - ($zi * $zi) + $cr" | bc)
  20. zi2=$(printf "%s\n" "scale=16; (($zr * $zi) * 2) + $1" | bc)
  21. temp=$(printf "%s\n" "(($zi * $zi) + ($zr * $zr)) > $BAILOUT" | bc)
  22. if ((temp == 1))
  23. then
  24. return "$i"
  25. fi
  26. if ((i > MAX_ITERATIONS))
  27. then
  28. return 0
  29. fi
  30. zr="$zr2"
  31. zi="$zi2"
  32. done
  33. }
  34. function mandelbrot {
  35. local y
  36. for ((y = -39; y < 39; y++))
  37. do
  38. printf "\n"
  39. local x
  40. for ((x = -39; x < 39; x++))
  41. do
  42. local xi
  43. local yi
  44. local ires
  45. xi=$(printf "%s\n" "scale=16; $x / 40.0" | bc)
  46. yi=$(printf "%s\n" "scale=16; $y / 40.0" | bc)
  47. iterate "$xi" "$yi"
  48. ires=$?
  49. if ((ires == 0))
  50. then
  51. printf "*"
  52. else
  53. printf " "
  54. fi
  55. done
  56. done
  57. printf "\n"
  58. }
  59. mandelbrot