How to resolve the algorithm Mandelbrot set step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Mandelbrot set step by step in the Nim programming language

Table of Contents

Problem Statement

Generate and draw the Mandelbrot set.

Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Mandelbrot set step by step in the Nim programming language

Source code in the nim programming language

import complex

proc inMandelbrotSet(c: Complex, maxEscapeIterations = 50): bool =
  result = true; var z: Complex
  for i in 0..maxEscapeIterations:
    z = z * z + c
    if abs2(z) > 4: return false

iterator steps(start, step: float, numPixels: int): float =
  for i in 0..numPixels:
    yield start + i.float * step

proc mandelbrotImage(yStart, yStep, xStart, xStep: float, height, width: int): string =
  for y in steps(yStart, yStep, height):
    for x in steps(xStart, xStep, width):
      result.add(if complex(x, y).inMandelbrotSet: '*'
                 else: ' ')
    result.add('\n')

echo mandelbrotImage(1.0, -0.05, -2.0, 0.0315, 40, 80)

import math, complex, lenientops
import imageman

const
  W = 800
  H = 600
  Zoom = 0.5
  MoveX = -0.5
  MoveY = 0.0
  MaxIter = 30

func hsvToRgb(h, s, v: float): array[3, float] =
  let c = v * s
  let x = c * (1 - abs(((h / 60) mod 2) - 1))
  let m = v - c
  let (r, g, b) = if h < 60: (c, x, 0.0)
                  elif h < 120: (x, c, 0.0)
                  elif h < 180: (0.0, c, x)
                  elif h < 240: (0.0, x, c)
                  elif x < 300: (x, 0.0, c)
                  else: (c, 0.0, x)
  result = [r + m, g + m, b + m]


var img = initImage[ColorRGBF64](W, H)
for x in 1..W:
  for y in 1..H:
    var i = MaxIter - 1
    let c = complex((2 * x - W) / (W * Zoom) + MoveX, (2 * y - H) / (H * Zoom) + MoveY)
    var z = c
    while abs(z) < 2 and i > 0:
      z = z * z + c
      dec i
    let color = hsvToRgb(i / MaxIter * 360, 1, i / MaxIter)
    img[x - 1, y - 1] = ColorRGBF64(color)

img.savePNG("mandelbrot.png", compression = 9)

  

You may also check:How to resolve the algorithm Determine if a string is squeezable step by step in the Clojure programming language
You may also check:How to resolve the algorithm Vampire number step by step in the zkl programming language
You may also check:How to resolve the algorithm Generator/Exponential step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the FOCAL programming language
You may also check:How to resolve the algorithm Sleep step by step in the Smalltalk programming language