You are on page 1of 79

19/11/2015

M andel brat set - Rosetta Code

Mandelbrot set
From Rosetta Code
This page uses content from Wikipedia (http://en.wikipedia.org) . The original article was at Mandelbrot set
(http://en.wikipedia.org/wiki/Mandelbrot_set) . The list of authors can be seen in the page history (http://en.wikipedia.Org/w/index.php?
title=Mandelbrot_set&action=history) . As with Rosetta Code, the text of Wikipedia is available under the GNU FDL
(http://www.gnu.org/licenses/fdl.html) . (See links for details on variance)

Generate and draw the Mandelbrot set.


Note that there are many algorithms
(http://en.wikibooks.org/wiki/Fractals/Iterations_in_the_complex_plane/Mandelbrot_set) to draw
Mandelbrot set and there are many functions
(http://en.wikibooks.org/wiki/Pictures_of_Julia_and_Mandelbrot_sets) which generate it.

E Mandelbrot set
You are
encouraged to solve this task
according to the task
description, using any
language you may know.

Contents

1ACL2
2 Ada
3 ALGOL 68
4 Applesoft BASIC
5 AutoHotkey
6 AWK
7 BASIC
7.1 BASIC256
7.2 BBC BASIC
7.3 Liberty BASIC
7.4 OS/8 BASIC
7.5 Run BASIC
7.6 Small BASIC
8 Befunge
9 Brace
10 Brainf***
11C
11.1 PPM non interactive
11.2 PPM Interactive
12 C++
13 C#
14 Clojure
15 D
15.1 Textual Version
15.2 More Functional Textual Version
15.3 Graphical Version
16 Dart
17 DEC BASIC-PLUS
18DWScript
19 Erlang
20ERRE
21 F#
22 Forth
23 Fortran
24GLSL
25 gnuplot
26 Go
27 Haskell
28 Haxe
29 Icon and Unicon
30IDL
31 Inform 7
32 J
33 Java

http://rosetlacode.0rg/wiki/M andel brot_set#M ATLAB

1/78

19/11/2015

M andel brat set - Rosetta Code

34 JavaScript
35 jq
36 Julia
37 Lab VIEW
38 Lang5
39 Lasso
40 Logo
41 Mathematica/Wolfram Language
42 Mathmap
43 MATLAB
44 Modula-3
45 MySQL
46Nim
47 OCaml
48 Octave
49 Pascal
50 Perl
51 Perl 6
52 Phix
53PHP
54 PicoLisp
55 PostScript
56 Prolog
57 PureBasic
58 Python
59 R
60 Racket
61REXX
61.1 version 1
61.2 version 2
61.3 version 3
62 Ruby
63 Scala
64 Scheme
65 Scratch
66 Sass/SCSS
67 Seed7
68 Sidef
69 Tel
70 TeX
71 TI-83 BASIC
72TXR
73 uBasic/4tH
74 Vedit macro language
75XPL0
76XSLT
77 Z80 Assembly
78 zkl

ACL2
(defun abs-sq (z)
(+
(expt
(realpart z)

(expt
(imagpart z)

2)
2)))

! defun round-decimal (x places)


!
(/ floor (* x (expt 10 places)) 1)
!
(expt
10 places)))

; defun round-complex (z places)


! (complex (round-decimal (realpart
!
(round-decimal
(imagpart

!
I

z) places)
z) places)))

!(defun mandel-point-r (z c limit)


;
(declare
(xargs :measure(nfix limit)))
;
cond
((zp limit) 0)
:
((> (abs-sq z) 4) limit)
!
(t (mandel-point-r (+ (round-complex
http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

j
J
!
I
;

;
;

(* z z) 15) c)

!
2/78

19/11/2015

M andel brat set - Rosetta Code


(1- limit)))))

(defun mandel-point (z iters)


(- 5 (floor (mandel-point-r z z iters) (/ iters 5))))
(defun draw-mandel-row (im re cols width iters)
(declare (xargs :measure (nfix cols)))
(if (zp cols)
nil
prog2$ (cw (coerce (list
(case (mandel-point (complex re im) iters)

(5 #\#)
(4 #\*)
(3 #\.)
(2 # \ . )

(otherwise #\Space))) 'string)) (drawmandel-row im


(+ re (/ (/ width 3)))
(1- cols) width iters))))
(defun draw-mandel (im rows width height iters)
(if (zp rows) nil
(progn$ (draw-mandel-row im -2 width width iters) (cw "~%")
(draw-mandel (- im (/ (/ height 2)))
(1- rows) width
height iters))))
(defun draw-mandelbrot (width iters)
(let ((height (floor (* 1000 width) 3333)))
(draw-mandel height width height iters)))

Output:

Ada
Library: Lumen
mandelbrot.adb:
with Lumen,Binary;
{package body Mandelbrot is
{ function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is !
type Lumen.Binary.Byte;
!
Result : Lumen.Image.Descriptor;
|
X0, Y0 : Float;
;
X, Y, Xtemp : Float;
;
Iteration : Float;
{
Max_Iteration : constant Float := 1000.0;
!
Color : Lumen.Binary.Byte;
! begin
j
Result.Width := Width;
|
Result.Height := Height;
;
Result.Complete := True;
;
Result.Values := new Lumen.Image.Pixel_Matrix (1 .. Width, 1 .. Height);
I
for Screen_X in 1 Width loop

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

use

3/78

19/11/2015

M andel brat set - Rosetta Code

for ScreenY in 1 .. Height loop


X0 := -2.5 + (3.5 / Float (Width) * Float Screen_X));
Y0 := -1.0 + (2.0 / Float (Height) * Float (Screen_Y));
X := 0.0;
Y := 0.0;
Iteration := 0.0;
while X * X + Y * Y <= 4.0 and then Iteration < Max_Iteration loop Xtemp
: = X * X - Y * Y + X0;
Y := 2.0 * X * Y + Y0;
X := Xtemp;
Iteration := Iteration + 1.0;
end loop;
if Iteration = Maxlteration then Color := 255; else
Color := 0;
end if;
Result.Values (Screen_X, Screen_Y) 2= (R => Color, G => Color, B => Color, A => 0); end loop; end
loop; return Result; end Create_Image;
end Mandelbrot;

mandelbrotads:
;with Lumen.Image;
package Mandelbrot is
! function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor; ;end Mandelbrot;

test mandelbrot.adb: with System.Address_To_Access_Conversions;


with Lumen.Window;
; iith Lumen.Image;
[with Lumen,Events;
Swith GL;
with Mandelbrot;

;
;
!
!
!

[procedure Test_Mandelbrot is

ProgramEnd : exception;

!
;
;

Win : Lumen.Window.Handle;
Image : Lumen.Image.Descriptor;
Tx_Name : aliased GL.GLuint;
Wide, High : Natural := 400;

!
!
;
J

!
!
!

-- Create a texture and bind


procedure CreateTexture is
use GL;

\
!
!

|
!
!
!
|
;

a 2D image to it

package GLB is new System.Address_To_Access_Conversions (GLubyte);


IP : GLpointer;
begin -- Create_Texture
-- ALLocate a texture name
glGenTextures (1, Tx_Name'Unchecked_Access);

;
!
!
I

-- Bind texture operations to the newLy-created texture name


glBindTexture (GL_TEXTURE_2D, Tx_Name);

\
\

!
;

-- Select modulate to mix texture with color for shading


glTexEnvi (GLTEXTUREENV, GL_TEXTURE_ENV_MODE, GLMODULATE);

!
j

;
!
!

-- Wrap textures at both edges


glTexParameteri (GL_TEXTURE_2D, GLTEXTURE WRAP S, GL REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

\
I
I

-- How the texture behaves when minified and magnified


glTexParameteri (GL_TEXTURE_2D, GLTEXTUREMINFILTER, GLNEAREST!;
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLNEAREST};

;
|
\

!
!

-- Create a pointer to the image. This sort of horror show is going to


- - b e disappearing once Lumen includes its own OpenGL bindings.
IP := GLB.To_Pointer (Image.Values.allAddress).all'Unchecked_Access;

!
'

|
:
!
!

-- Build our texture from the image we loaded earlier


glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,
GLRGBA, GL_UNSIGNED_BYTE, IP);
end Create_Texture;

http://rosetlacode.org/wiki/M andel brot_sel#M ATLAB

\
!
!
!

4/78

19/11/2015

M andel brat set - Rosetta Code

-- Set or reset the window view parameters procedure


SetView (W, H : in Natural) is use GL;
begin -- Set_View
GL.glEnable (GL.GL_TEXTURE_2D); glClearColor (0.8,_0.8, 0.1, 1.0);
glMatrixMode (GL_PR03ECTI0N); glLoadldentity;
glViewport (0, 0, GLsizei (W), GLsizei (H));
glOrtho (0.0, GLdouble (W), GLdouble (H), 0.0, -1.0, 1.0);
glMatrixMode (GL_MODELVIEW); glLoadldentity; end Set_View;
-- Draw our scene procedure Draw is use GL;
begin -- Draw
-- clear the screen
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);
-- fill with a single textured quad glBegin (GL_QUADS);
begin
glTexCoord2f (1.0, 0.0); glVertex2i
(GLint (Wide), 0);
glTexCoord2f (0.0, 0.0); glVertex2i
(0, 0);
glTexCoord2f (0.0, 1.0); glVertex2i
(0, GLint (High));
glTexCoord2f (1.0, 1.0); glVertex2i (GLint (Wide),
GLint (High)); end; glEnd;
-- flush rendering pipeline glFlush;
-- Now show it Lumen.Window.Swap (Win); end Draw;
-- Simple event handler routine for keypresses and close-window events procedure
Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise
ProgramEnd; end Quit_Handler;
-- Simple event handler routine for Exposed events procedure ExposeHandler (Event :
in Lumen.Events.Event_Data) is pragma Unreferenced (Event); begin -Expose_Handler Draw;
end ExposeHandler;
-- Simple event handler routine for Resized events
procedure ResizeHandler (Event : in Lumen.Events.Event_Data) is begin -Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
SetView (Wide, High);
Image := Mandelbrot.Create_Image (Width => Wic/e, Height => High); Create_
Texture;
Draw;
end ResizeHandler;
begin
-- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity
=> Win,
"Mandelbrot fractal",
Lumen.Window.Create (Win
Name => Width => Wide,
Height => Events High,
(Lumen.Window.Want_Exposure => True,
=>
Lumen.Window.Want_Key_Press => True, others
=>
False));
-- Set up the viewport and scene parameters SetView (Wide, High);
-- Now create the texture and set up to use it
Image := Mandelbrot.Create_Image (Width => Wide, Height => High); Create_Texture;

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

5/78

19/11/2015
-- Enter the event Loop
declare
use Lumen.Events;
begin
Select_Events (Win
Calls

M andel brat set - Rosetta Code

=>
=>

Win,
(Key_Press
Exposed
Resized
Close_Window
=> others

=> Quit_Handler'Unrestricted_Access,
=> ExposeHandler'UnrestrictedAccess,
=> ResizeHandler'UnrestrictedAccess,
Quit_Handler'Unrestricted_Access,
=> NoCallback));

end;
exception
when ProgramEnd => null;
end Test_Mandelbrot;

Output:

ALGOL 68
Works with: Algol 68 Genie 1.19.0
Plot part of the Mandelbrot set as a pseudo-gif image.

jINT pix = 300, max iter = 256, REAL zoom = 0.33 / pix;
[[-pix : pix, -pix : pix] INT plane;
[COMPL ctr = 0.05 I 0.75 # center of set #;
I# Compute the Length of an orbit. # jPROC
iterate = (COMPL z0) INT:
| BEGIN COMPL z := 0, INT iter := 1;
;
WHILE (iter +:=
1) < max iter # not converged # AND ABS z < 2 # not diverged #
;
D O z : = z * z + z 0
I
OD;
!
iter
I END;
[# Compute set and find maximum orbit Length. #
[INT max col := 0;
[FOR x FROM -pix TO pix IDO
FOR y FROM -pix TO pix
I DO COMPL z0 = ctr + (x * zoom) I (y * zoom);
;
IF (plane [x, y] := iterate (z0)) < max iter
[ THEN (plane [x, y] > max col | max col := plane [x, y])
! FI : OD
lOD;
j# Make a pLot. #
[FILE plot;

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

6/78

19/11/2015

M andel brat set - Rosetta Code

jINT num pix = 2 * pix + 1;


;make device (plot, "gif", whole (num pix, 0) + "x" + whole (num pix, 0));
[open (plot, "mandelbrot.gif, stand draw channel);
[FOR X FROM -pix TO pix !DO FOR y
FROM -pix TO pix
! DO INT col = (plane [x, y] > max col | max col | plane [x, y]);
;
REAL c = sqrt (1- col /max col); # sqrt to enhance contrast #
;
draw colour (plot, c, c, c);
[
draw point (plot, (x + pix) / (num pix - 1), (y + pix) / (num pix - 1))
[ OD lOD;
close (plot)

Applesoft BASIC
This version takes into account the Apple II's funky 280^192 6-color display, which has an effective resolution of only 140x192 in color.

:10
20
[30
140
45
50
60
[70
[80
[90
!l00
11
0
12
0
[130

HGR
2 =
XC
YC =
s=
IT =
XR =
YR =
X0 =
XI =
Y0 =
Yl =
XM =
YM =
FOR

-0.5
0
2
20
S*4/3
S
XC - (XR/2)
XC + (XR/2)
YC - (YR/2)
YC - (YR/2)
XR / 279
YR / 191
/1 = 0 TO 3

REM
REM
REM
REM
REM
REM
REM
REM
REM
REM
REM
REM
REM

CENTER
X
COORD
""
Y
SCALE
ITERATIONS
TOTAL RANGE
OF
""
MIN VALUE OF X
MAX
X
MIN
Y
MAX
Y
SCALING
FACTOR
""
INTERLEAVE

[140 FOR YS = 0+YI TO 188+YI STEP 4 : REM Y SCREEN COORDINATE [145


HCOLOR=3
: HP LOT 0,YS TO 279, YS
!l50
FOR XS
= 0 TO 278STEP 2
: REMXSCREENCOORDINATE
170
X = XS * XM + X0: REM TRANSL SCREENTOTRUE X
180
Y = YS * YM + Y0: REM TRANSL SCREENTOTRUE Y
[190
ZX = 0
[200
ZY = 0
[210
XX = 0
1220
YY = 0
230
FOR I = 0 TO IT
240
Z Y = 2 * Z X * Z Y +Y
[250
ZX
= XX - YY + X
[260
XX
= ZX *ZX
[270
YY
= ZY *ZY
1280
C = IT-1
290
IF
XX+YY
>= 4 GOTO 301
300
NEXT
I
[301
IF C >= 8 THEN C
= C - 8 : GOTO 301
[310
HCOLOR= C : HP LOT XS, YS TO XS+1, YS
[320
NEXT XS
1330 NEXT YS 340
NEXT YI

By making the following modifications, the same code will render the Mandelbrot set in monochrome at full 280x192 resolution.

150 FOR XS = 0 TO 279


301 C = (C - INT(C/2)*2)*3
310 HCOLOR = C: HPLOT XS, YS

AutoHotkey
Max_Iteration := 256 Width :=
Height := 400
[File := "MandelBrot." Width ".bmp"
[Progress, b2 w400 fs9, Creating Colours ...
iGosub, CreateColours
iGosub, CreateBitmap
[Progress, Off
[Gui, -Caption
[Gui, Margin, 0, 0
[Gui, Add, Picture,, %File%
iGui, Show,, MandelBrot
Return

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

7/78

19/11/2015

M andel brat set - Rosetta Code

iGulClose:
<5uiEscape:
jExitApp

|CreateBitmap: ; create and save a 32bit bitmap file


; define header detail.s
HeaderBMP := 14 HeaderDIB :=
40
DataOffset := HeaderBMP + HeaderDIB ImageSize :=
Width * Height * 4 ; 32bit FileSize := DataOffset +
ImageSize Resolution := 3780 ; from mspaint ; create
bitmap header VarSetCapacity(IMAGE, FileSize, 0)
NumPut(Asc("BM)
, IMAGE, 0x00, "Char)
NumPut(Asc("M")
, IMAGE, 0x01, "Char")
NumPut(FileSize
, IMAGE, 0x02, "Ulnt")
NumPut(DataOffset
, IMAGE, 0X0A, "Ulnt")
NumPut(HeaderDIB
, IMAGE, 0x0E, "Ulnt")
NumPut(Width
, IMAGE, 0x12, "Ulnt")
NumPut(Height
, IMAGE, 0x16, "Ulnt")
NumPut(1
, IMAGE, 0xlA, "Short")
; Planes ; Bits per
NumPut(32
, IMAGE, 0xlC, "Short")
Pixel
NumPut(ImageSize
, IMAGE, 0x22, "Ulnt")
NumPut(Resolution
, IMAGE, 0x26, "Ulnt")
NumPut(Resolution
, IMAGE, 0x2A, "Ulnt")
; fill in Data Gosub, CreatePixels ;
save Bitmap to file FileDelete,
%File%
Handle := DllCall("CreateFile", "Str", File, "Ulnt", 0x40000000 , "Ulnt", 0, "Ulnt", 0,
"Ulnt", 2, "Ulnt", 0, "Ulnt", 0) DllCall("WriteFile", "Ulnt", Handle, "Ulnt", &IMAGE, "Ulnt"
, FileSize, "Ulnt Bytes, "Ulnt", 0) DllCall("CloseHandle", "Ulnt",
Handle)
Return

CreatePixels: ; create pixels for [-2 < x < 1] [-1.5 < y < 1.5]
Loop, % Height // 2 + 1 {
yi := A_Index - 1
y0 := -1.5 + yi / Height * 3 ; range -1.5 .. +1.5
Progress, % 200*yi If Height, % "Current line: " 2*yi " / " Height
Loop, %Width% {
xi := A_Index - 1
x0 := -2 + xi / Width * 3 ; range -2 .. +1
Gosub, Mandelbrot
pi := DataOffset + 4 * (Width * yi + xi)
NumPut(Colour, IMAGE, pi, "Ulnt")
p2 := DataOffset + 4 * (Width * (Height-yi) + xi)
NumPut(Colour, IMAGE, p2, "Ulnt")
>
>

Return

Mandelbrot: ; calculate a colour for each pixel


x := y := Iteration := 0
While, (x*x + y*y <= 4) And (Iteration < Maxlteration) { xtemp := x*x - y*y +
x0 y := 2*x*y + y0 x := xtemp Iteration++
}
Colour := Iteration = Max_Iteration ? 0 : Colour_%Iteration%
Return

........
[CreateColours: ; borrowed from PureBasic example
Loop, 64 {
i4 := (i3 := (12 := (il := A_Index - 1) + 64) + 64) + 64 Colour_%il% := RGB(4*il + 128, 4*il,
0)

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

8/78

19/11/2015

M andel brat set - Rosetta Code

Colour_%i2% : = RGB , 255, 4*il)


Colour_%i3% : = RGB
, 255 - 4*il, 255)
ColourJSi4% : = RGB
, 0, 255 - 4*il)

}
Return

RGB(r, g, b) { ; return 24bit color value


Return, (r&0xFF)16 | g | b

AWK
BEGIN {
XSize=59; YSize=21;
Minim1.0; Maxlm= ,0;MinRe=-2.0; MaxRe-1.0;
StepX= MaxRe-MinRe /XSize; StepY= Maxim-Minim /YSize;
for(y=0;y<YSize;y++)
{
Im=MinIm+StepY*y;
for(x=0;x<XSize;x++)
{
Re=MinRe+StepX*x; Zr=Re; Zi=Im;
for(n=0;n<30;n++)
{
a=Zr*Zr; b=Zi*Zi;
if(a+b>4.0) break;
Zi=2*Zr*Zi+Im; Zr=a-b+Re;
>

printf "%c",62-n;

j
print
}
exit;

j
=====<<< >===<<;;: =96032:;;;;==== ;:: =
===<<<;;;;;;;: :9974
873*079: :;;;;<=
>==<;;;;;;: >8888764
(.9::: :;;<======
>>==<<<<<<<<<<<<<;j;j::::996. 82
5789999: ;;<====
= < ; : 9 9 9 7 5 2 >=;;;
45335: ;<<<<=== *79:
=599999999886
;== %78: ;;=
+9;;< *9;;; 8:;;;
889:;;; 889:;;;
>
: =972456-567763
8:;;; *9;;; +9;;<
::=98758
.3
><;;; ^
%78:;;<<= *79: ;==
=997564'
jjjj
45335:;=== 5789999:
>:=988897735/
;;<====
>:=988897735/
(.9::::;;<<<<<======
=997564'
=98758
.3
> ; = 9 7 2 4 5 6 - 5 6 7 7 6 3 >=;;;
=599999999886
=<;=999752
==<;;;;::: =996. 82
>==<;;;;;
98888764
;;:=9974
===<;;;

>===<<;

BASIC
Works with: QBasic
This is almost exactly the same as the pseudocode from the Wikipedia entry's "For programmers" section (which it's closely based on, of course).
The image generated is very blocky ("low-res") due to the selected video mode, but it's fairly accurate.
i---------------------------------------------------------------------------------------------------------------------------------------------------- y

SCREEN 13
WINDOW (-2, 1.5)-(2J -1.5)
FOR x0 = -2 TO 2 STEP .01
| FOR y0 = -1.5 TO 1.5 STEP .01

!
|
|
|

x=0

y =0

iteration = 0
maxlteration =

223

WHILE (x * x +

y * y <=(2 * 2) AND iteration < maxlteration)

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

9/78

19/11/2015

Mandelbrot set - Rosetta Code


xtemp = x * x - y * y + x 0
y - 2 x * y + y 0

xtemp

iteration

WEFO

!
;
;

IF iteration
c ELSE

c =

iteration + 1

<>maxlteration THEN
iteration

EM3 IF

;
; NEXT
NEXT

PSET (X0,

y0),

C +32

BASIC256
Ifastgraphics

|graphsize 384,384
[refresh
[kt=319 : m = 4.0
Jxmin=2.1 : xmax=-0.6 : ymin=-1.35 : ymax=1.35 ldx=(xmaxxmin)/graphwidth : dy=(ymax-ymin)/graphheight
[for x=0 to graphwidth [
jx =
xmin+x*dx
[
for y=0
to
graphheight
!
jy = ymin+y*dy
!
k = 0 : wx =
0.0
I
do

;
;
[
!
!
I

: wy = 0.0

tx = wx*wx-(wy*wy+jx)
ty = 2.0*wx*wy+jy
wx = tx
wy = ty
r - wx*wx+wy*wy
k = k+1
until r>m or k>kt

[
!
!
j

if k>kt then
color black
else
if k<16 then color k*8,k*8,128+k*4

j
;
[
!
!
!

if k>-16 and k<64 then color 128+k-16,128+k-16,192+k-16


if
k>=64 then color
kt-k,128+(kt-k)/2,kt-k
end if
plot x,y
next y
refresh

[next x
[imgsave "Mandelbrot_BASIC-256.png", "PNG"

Image generated by the script:

BBC BASIC
Works with: BBC BASIC for Windows
sizexX - 300 : sizey% - 300 maxiter% =
128
VDU 23,22,sizex%;sizeyXj8,8,16,128
ORIGIN 0,sizey%
GCOL 1
FOR X% = 0 TO 2*sizex%-2 STEP 2 xi
http^/rosettacode.org/wiki/M andel brot_s^\/IATI_AB

10/78

19/11/2015

M andel brot set - Rosetta Code

= X%/200 - 2 FOR Y% = 0 TO sizey%-2


STEP 2 yi = Y% / 200 x = 0
y=0

FOR 1% = 1 TO maxiter%
IF x*x+y*y > 4 EXIT FOR xt =
xi + x*x-y*y y = yi + 2*x*y x = xt
NEXT
IF I%>maxiter% I%=0
COLOUR 1,I%*15,I%*8,0 PLOT
X%jY% : PLOT X%j-Y% NEXT NEXT X%

Liberty BASIC
Any words of description go outside of lang tags.
;nomainwin

IWindowWidth =440
IWindowHeight =460
[Open "Mandelbrot Set" for graphics_nsb_nf as #w
|#w "trapclose [quit]"
!#w "down"
rfor X0 = -2 to 1 step .0033 ; for y0 = -1.5 to 1.5
step .0075

x=0
:
y=0
!

iteration
maxlteration =

;
;
!
!
!

while ( ( x *x +y *y) <=4) and ( iteration <maxlteration)


xtemp
=x *x -y
*y+x0
y
=2 *x *y
+y0
x
= xtemp
iteration = iteration
+1

wend

!
!

if iteration omaxlteration then


c iteration

else

0
255

c =0

end if

call pSet x0, y0, c


!
scan
! next In ext

#w "flush"
Iwait

http://rosetlacode.org/wiki/M andel brot_set#MATLAB

11/78

19/11/2015

M andel brat set - Rosetta Code

sub pSet x, y, c
xScreen = 10 +( x +2)
/3 *400
yScreen = 10 +( y +1.5) /3 *400 if c =0
then col$ ="red"
else
if c mod 2 =1 then col$ ="lightgray" else col$ ="white"
end if
#w "color col$
#w "set "; xScreen; " "; yScreen
end sub
[quit] close #w end

OS/8 BASIC
Works under BASIC on a PDP-8 running OS/8. Various emulators exist including simhs PDP-8 emulator and the PDP-8/E Simulator
(http://www.bemhard-baehr.de/pdp8e/pdp8e.html) for Classic Macintosh and OS X.
10 X1=59\Y1=21
J20 Il=-1.0\I2=1.0\Rl=-2.0\R2=1.0
J30 S1=(R2-R1)/X1\S2=(I2-I1)/Y1
40 FOR Y=0 TO Y1
50 I3=I1+S2*Y
60 FOR X=0 TO XI
70 R3=R1+S1*X\Z1=R3\Z2=I3
[80 FOR N=0 TO 30
190 A=Z1*Z1\B=Z2*Z2
!l00 IF A+B>4.0 GOTO 130
jll0 Z2=2*Z1*Z2+I3\Z1=A-B+R3
120 NEXT N
130 PRINT CHR$(62-N);
;i40 NEXT X 1150 PRINT 160 NEXT Y jl70 END

Output:
,>>>>>>=====<<<<<<<<<<<<<<<

;:::96032:; ;;;===========
:::873*079::;; ;;<========
!>>===<<<<<<<<<<<;;;;
(.9::::;;<<<<<=======
9974
[>>>==<<<<<<<<<<<<<<<;;;;;;
5789999: ;;<=====
98888764
;>>==<<<<<<<;;;;::: :996. &2
45335:;====
:=<<<;;;::::: :999752 !>=;; ;:
*79:; <<===
599999999886

!>===<<;;

%78:; ;<<<<<<==
+9; ;<<<<<<<
*9; =

><<

::972456-567763
::::9875&
.3
;><;;; \>;
:997564'
!>:: 988897735/
988897735/
997564'
:9875&
.3
: : :972456-567763
;>=;;;: 599999999886
!=<<<;;:999752
!>>==<<<<<<<<<<<<<;;;;::::996. &2
>>>==<<<<<<<<<<<<<<<;;;;;;
>>>>===<<<<<<<<<<<<<<<;;;;

;>===<<;;
;>>>>=====<<<<<<<<<<<<<<<

8: ; ;;<<<<<<=

98888764
9974

&89:; ;;<<<<<<=
&89:; ;;<<<<<<=
8: ; ;;<<<<<<=
*9; ;;<<<<<<=
+9; ;;<<<<<<=
%78:; ;<<<<<<<
*79:; =
45335:;====
;<<<<<<==
<<===
5789999:;;
<=====
(.9: :::;;<=======
:::873*079::;;;;<<<<<========
;:: :96032: ;;;;===========

Run BASIC
Mandelbrot V4 for RunBasic
Based on LibertyBasic solution
['copy the code and go to runbasic.com
1'http://rosettacode.0rg/wiki/Mandelbrot_set#Liberty_BASlc
I'May 2015

;
;
;
!

IWindowWidth = 320 'RunBasic max size 800 x 600


WindowHeight = 320
print zone -2 to 1 (X)
[print zone -1.5 to 1.5 (Y)
!a = -1.5 'graph -1.5 to -0.75, first
"loop"
!b = -0.75 adjust for max processor time (y0 for loop below)

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

!
!

12/78

19/11/2015

M andel brat set - Rosetta Code

[open "Mandelbrot Set" for graphics_nsb_nf as #w not used in RunBasic


Sgraphic #w, WindowWidth, WindowHeight
!#w "trapclose [quit]
not used in RunBasic
!'#w "down"
not used in RunBasic
;cls
|'#w flush()
!#w cls("black")
Srender #w j '#w
flush()

jinput "OK, hit enter to continue"; guess els


![man_calc]
I'3/screen size 3/800 = 0.00375 ** 3/790 = 0.0037974 I'3/screen size (y)
3/600 = .005 ** 3/590 = 0.0050847 j'3/215 = .0139 .0068 = 3/440 jee =
3/299

!
!
!
|

for x0 = -2 to 1 step cc
for y0 - a to b step cc
x=0
Y=0

|
S

iteration =
maxlteration = 255

while ( ( x *x +y *y) <=4) and ( iteration <maxIteration)

j
!
!
S

xtemp
=x *x -y
y
=2 *x *y
x
= xtemp
iteration = iteration
wend

;
;
I
S

if iteration omaxlteration then


c =iteration
else
c =0
end if

|
;

call pSet x0, y0, c


'scan why scan? (wait for user input) with RunBasic ?

*y +x0
+y0
+1

|
next
Snext

i'#w flush() 'what is flush? RunBasic uses the render command.


[render #w

[input "OK, hit enter to continue"; guess [els


!a a + 0.75 |b =
b + 0.75
jif b > 1.6 then goto[quit] else goto[man_calc]
[sub pSet x,
[
xScreen
!
yScreen

y, c
= 5+(x
5+(y

+2) /3
+1.5) /3

* 300 'need positive screen number


* 300 'and 5x5boarder

if c =0
then
col$ ="red"

; else
[
[ end if

if c mod 2 =1 then col$ ="lightgray" else col$ ="white"

! #w "color "; col$

! #w "set "; xScreen; ; yScreen ;end sub


[[quit]
!cls
Srender #w

Iprint "All done, good bye.


end

Small BASIC
i ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

lGraphicsWindow.Show() ! [size 500 ; [half = 250 ; [GraphicsWindow.Width = size * 1.5 [ [GraphicsWindow. Height = size
size * 1.5 ; x_0 = px/half - 2 ; ; For py = 1 To size ; ; y_0 = py/half - 1 [ [ x = x_0 [

S [GraphicsWindow.Title = "Mandelbrot" S For px 1 To

y = y_0
i=0

While(c <= 2 AND i<100)


x_l = Math.Power(x, 2) - Math.Power(y, 2) + x_0 y_l = 2 * x
* y + y_0
c = Math.Power(Math.Power(x_l., 2) + Math.Power(y_l, 2)., 0.5) x = x_l
y = y_i

i - i + 1 EndWhile If i < 99 Then


GraphicsWindow.SetPixel(px, py, GraphicsWindow.GetColorFromRGB((255/25)*i, (255/25)*i, (255/5)*i)) Else
GraphicsWindow.SetPixel(px, py, "black")
Endlf
c=0
EndFor
EndFor

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

13/78

19/11/2015

M andel brat set - Rosetta Code

Befunge
Using 14-bit fixed point arithmetic for simplicity and portability. It should work in most interpreters, but the exact output is
implementation
dependent, and some will be unbearably slow.
X scale is (-2.0, 0.5); Y scale is (-1,1); Max iterations 94 with the ASCII character set as the "palette".
0>:00p58*'#@_0>:01p78vv$$
<
gA+lg00,+55 v# !'\+*9<>4v$
J@v30p20"?~A"< A+lgl0,+*8<$
$>p0\>\::882**02g*0v >A

|<

d":+*:-*,,[Z,,+g3 <
V-*"[Z"+g30*g20**288\--\<#
>2**5#>8*:*/00g"P"*58*:*vA
V*288 p20/**288:+*"[Z"+-<:
>*%03 p58*:*/01g"3"* v>::A
\_A#!:-l\+-*2*:*85<A

Output:

}>}}}}}}>! t i l l 1 !{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzyyyyxwusjuthwyzzzzzzz{{{{{{{
}}}}! 1 1111 K{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzyyyyxwwvtqptvwxyyzzzzzzz{{{{{
}}}}>}}!1 1 11!{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyyxwvuqaZlnvwxyyyzzzzzzz{{{{
}}}}!1 1 1 l{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyyxxvqXp g Ynslvxyyyyyzzzzz{{{
6puwxyyyyyyzzzz{{
>>>>}}
111!{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyxxxxw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
1 1 {{{{{{{{{{{{{{{{{zzzzyyyyyyyyyyyxxxxwvrrrkC
}}>
11{{{{{{{{{{{{{{{{{{{zzzzyyyyyyyyyyxxxwvusg
} } > 1 1 {{{{{{{{{{{{{{{{{{{{{zzzzzzyyyyyyyxxxwurf
ZnW
>>>>1!{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzyyyyyxwvqenirttj m id+
}}>> 11 !{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzyyyywwvtvvvvuutsp
}l 1 | |{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzyyyxxxxxwwvvqc

ntwx
nsvx
Ufwy
$uxy
twxy
auwxxy
dqtvwxyy
auwxxy
twxy
$uxy
Ufwy
nsvx
ntwx
hjx
ptuox
ptvwxy
grwxxy

Uquxyy
4nrslnobgwyy
PRUiPp rvvwudwxyz
H rt uuvwxxxxwqxyzz

&8 uvwxxxyyyyyz z

6puwxyyyyyyzzzz{{
}}>}!
11!{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyxxxxwvtp
z{
> > > > > } 1 1 1 1 l{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyyxxvqXp
g Ynslvxyyyyyzzzzz{{{
}}}}}}}!1 1 11|{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzyyyyxwvuqaZlnvwxyyyzzzzzzz{{{{
}}}}>}}>111 1 1 1 !{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzyyyyxwwvtqptvwxyyzzzzzzz{{{{{
}}}}}}}}}! t i l l 1 !{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzyyyyxwusjuthwyzzzzzzz{{{{{{{
A

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

14/78

19/11/2015

M andel brat set - Rosetta Code

This is a simple Mandelbrot plotter. A longer version based on this smooths colors, and avoids calculating the time-consuming black pixels: http
://sam. ai.ki/brace/examples/mandelbrot. 6J1

Brace
I#!/usr/bin/env bx iuse b
MainO:
;
!
|
!
|
|
;
!
!

;
;
;

num outside = 16, ox = -0.5, oy = 0, r = 1.5


long i, m a x i = 100, rb_i =30
space/)
uint32_t *px =
pixel()
num d = 2*r/h,
x0 = ox-d*w_2, y0 = oy+d*h_2
for(y, 0, h):
cmplx c = x0 + (y0-d*y)*I
repeat(w):
cmplx w = 0
for i=0; i < max_i && cabs(w) < outside; ++i
w = w*w + c
*px++ = i < m a x i ? rainbow(i*359 / rb_i % 360) : black
c += d

An example plot from the longer version:

; A mandelbrot set fractal viewer In brainf*ck written by Erik Bosman


M-++++++++++++[->++>+++++>++>+<<] >++++++> ---------------- >>>>>>>>>>+++++++++++++++[ [

:>]+[<]>-]+[[-]>]<[<][-]+
;<+++++[-[->+<]>]
>+
!>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[]>>]<<<<<<<<<[<<<<<<<<<]>> i>[-]+<<++++[-[->+<]>] +<<+++++++[-[->
;>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
;>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
;[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
;]>[-<+>]< [->++< ]>+++++++++++++++[[ l>]+>[-]>[-]>[-]>[-]>[-]>[]>[-]>[-]>[-]<<<<<<<<< [<]>-]+[ !>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[<<<<+>>>>]<<<<[->>>>+<<<<<[->>[
-<<+][->>++<<<<]+>>>>>]<<<<[<<<<<<<<<]
]>[>]<
;<<[>[->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[>>>>>>>>>+<<<<<<<<<]<+>>>>>>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[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[>[->>>>

:>+<]]>[->+<]<+]<[>[-]<->
<+>]<

[->+<]>][-+]<+<]>[

[-<

:[-<+>[<->-

!+>]<[-

>++<]]<[<]>[>+
;]<<<[<<<<<]>>>>>>>[>->>>[-<<<+>>>>>]<<<<<[->>>+<<<<[-[-<<+
>>+>>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[>
>>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<<[>[-

http://rosettacode.Org/wiki/M andel brot_set#M ATLAB

;>>]<<[:[-

15/78

19/11/2015

M andel brat set - Rosetta Code

[->>>+<<<]<+<<<<<<<<<] >>>>>>>>> ;[[+ !]>>>]<<<<<<<<<[<<<<<<<<<] >>>>>[>[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>


;]<-[-<<<<+>[<->-<<<<<<+>>]<

>+<]>>>>]<<<

!>]]<[<]>++++++++ *++++++[[>]<<[<]>-]+[[-<+
>>>]<<<<<<<
[->>>>>>>+<<<<<<+<
]>>]<<<<<<<<<[<<<<<<<<<]>>>>>[>>>>[ ;-]>]<<<<<<<<<[<<<<<<<<<]>>+> [-<-<<+>>>>>] >[<<<<<<[ ->>>>>+<++<<<<] >>>[-< :<<<<+>]<->+>]< [ - >+< ]<<<<< [->>>>>+< ]>>>>>>[]<<<<<<+>>>>[-<<<<->>]+<<<<
H->>[>>>>>] >+< ] ]+>>>[-<<<->>>]+<<<[->>>-<[-<<+>>]<< [ ->>+<<<<<<<<<<<[<<<<<

!] [-]+>[>]>[-]+<]]+>[-<[>] ]]<<<
;[<<<] >>[-<<<<+>>>>]<<<< [ ->>>>+>[>+>>[-<<->>]<<[ ->>+<<]>>>>]<<<<< ;<+<[>[>+[--+>[->+<]<]>[->-<
;<+>]]>[-+<[->+>]<]>[->+<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CCCCCCCCCBBBBBBB
lAAAAAAAAAAAABBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEEFFGHIMTKLZOGFEEDDDDDDDDDCCCCC
BBBBB
CCCCBBBBBBBBBBBBBBBBBBBBB
AAAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDEEEEFFFI
ZQL[MHFEEEEEEEDDDDDDDCCCCCCCCCCCBBBBBBB
KHGGGHGEDDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBB X
IAAAAAAAAAAAAAAABBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDEEEFGIIGFFEEEDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBBBBB
KHHGFEEEEEDDDDDDDDDCCCCCCCCCCBBBBBBBBB
BBBBBBB

PPM non interactive


Here is one file program. It directly creates ppm file.
/*

c program:
1. draws Mandelbrot set for Fc(z)=z*z +c
using MandeLbrot algorithm ( boolean escape time )

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

17/78

19/11/2015

M andel brat set - Rosetta Code

2. technique of creating ppm file is based on the code of Claudio Rocchini


http://en.Wikipedia.org/wiki/Image:CoLor_compLex_pLot.jpg
create 24 bit color graphic file , portable pixmap file = PPM
see http://en.wikipedia.org/wiki/Portablejpixmap
to see the file use external application ( graphic viewer)
*/

#include <stdio.h> int main()

{
/* screen ( integer) coordinate */ int iX,iY;
const int iXmax = 800; const int iYmax = 800;
/* world ( double) coordinate = parameter plane*/

double Cx,Cy;
const double CxMin=-2.5;
const double CxMax=1.5;
const double CyMin=-2.0;
const double CyMax=2.0;

/* */
double PixelWidth=(CxMax-CxMin)/iXmax; double
PixelHeight= CyMax-CyMin)/iYmax;
/* color component ( R or G or B) is coded from 0 to 255 */
/* it is 24 bit color RGB file */ const int
MaxColorComponentValue=255;
FILE * fp;
for (Iterations;Iteration<IterationMax && ((Zx2+Zy2)<ER2);Iteration++) {
Zy=2*Zx*Zy + Cy;
Zx=Zx2-Zy2 +Cx;
Zx2=Zx*Zx;
Zy2=Zy*Zy;

>;
/* compute pixel coLor (24 bit = 3 bytes) */ if (Iteration==IterationMax { / interior of
Mandelbrot set = black */ color[0]=0; color[l]=0; color[2]=0;

}
else

{ /* exterior of Mandelbrot set = white */ color =

; /* Red*/

color[1]=255;
/* Green */
color[2]=255;/* Blue /

}J
/write color to the file*/ fwrite(color,1,3, fp);

}
}
fclose(fp);
return 0;

char *filename="newl.ppm";
char comments# ";/* comment should start with # */ static
unsigned char color[3];
/ Z=Zx+Zy*i ; Z0 = 0 */ double ZXj Zy;
double Zx2j Zy2; /* Zx2=Zx*Zx; Zy2=Zy*Zy */

/* v

int Iteration;
const int IterationMax=230;
/* bail-out value , radius of circle ;
*/
const double EscapeRadius=2;
double ER2=EscapeRadius*EscapeRadius;
/*create new file,give it a name and open it in binary mode */ fp=
fopen(filenameJ,,wb"); /* b - binary mode */
/write ASCII header to the file*/
fprintf(fp,"P6\n %s\n %d\n %d\n %d\n"jcomment,iXmax,iYmaXjMaxColorComponentValue ; / compute
and write image data bytes to the file*/ for(iY=0;iY<iYmax;iY++)
{
Cy=CyMin + iY*PixelHeight;
if (fabs(Cy)< PixelHeight/2) Cy=0.8; /* Main antenna */
for(iX=0;iX<iXmax;iX++)

{
Cx=CxMin + iX*PixelWidth;
/* initial value of orbit = critical point Z= 0 */
Zx=0.0;
Zy=0.0;
Zx2=Zx*Zx;
Zy2=Zy*Zy;

/* */

PPM Interactive

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

18/78

19/11/2015

Mandelbrot set - Rosetta Code

Infinitely zoomable OpenGL program. Adjustable colors, max iteration, black and white, screen dump, etc. Compile with

gcc mandelbrot. c -lglut

-1GLU -1GL -lm

OpenBSD users, install ireeglut package, and compile with make mandelbrot CPPFLAGS='-i/usr/local/include 'pkg-config glu -- cflags'1 LDLIB5=-L/usr/local/lib -lglut 'pkgconfig glu libs' -lm'

Library: GLUT
IfrincLude <stdio.fi > f incLude <stdLib.h> pinelude <aath.fi>
Pinclude <GL/glut.h> pine hide <GL/gL.h>
\ incLude <GL/gLu.h>
void set_texture();
ttypedef struct {unsigned char r, g, b; rgb_t;

!rgb_t **tex = 0; lint gwin;


GLuint texture; jlnt width, height;
int tex_w, tex_h; jdouble scale - 1./256;
[double cx = -.6, cy = 9; lint color_rotate = 0; lint saturation = 1;
int invert - 6; jint max_lter - 256;
[void renderQ

*
j

double x = (double)width /tex_w,

y = (double)height/tex_h;

glClear(GL_COLOR_BUF FER_BIT);

glTexEnvi(GL_TEJOURE_ENV, GL_TEXTURE_ENV_MOOE, GL_REPLACE);

glBindTexture(GL_TEXTURE_2D, texture);

glBegin(GLJQUADS);

!
!
j

glTexCoord2f(0,
glTexCoord2f(x,
glTexCoord2f(x,
glTexCoord2f(0,

j
!

glEnd();
glFlushQ;

glFinish();

0);
0);
y);
y);

glVertex2i(0, 0);
glVertex2i(width, 0);
glVertex2i(width,
height);
glVertex2i(0, height);

Jint dump = 1;
[void 5creen_dump()

fc
!

char fn[100];

j
;

int i;
sprintf(fn, "screenX03d.ppm", dump++);

!
!
!

FILE *fp = fopen(fn, "w*);


fprintf(fp, "P6\nXd J6d\n255\n", width, height);
for (i = height - 1; i >= 0; i--)

fwrlte(tex[i], 1, width * 3, fp);

hittp//rosettacode.or9^wiki/Mandel brot_set#M ATLAB

19/78

19/11/2015
fclose(fp);
printf("%s written\n", fn);

Ivoic keypress (unsigned


!{

switch(key) {
;
case 'q':

case

M andel brat set - Rosetta Code

char key, int x, int y)

glFinish();
glutDestroyWindow(gwin);
return;
= 1./256; cx = -.6; cy = 0; break;

7:scale

case r:

color_rotate = (color_rotate + 1) % 6; break;

case 1 >': case


max_iter += 128;
if (maxiter > 1 15) maxiter = 1 << 15; printf("max iter:
%d\n", max_iter); break;

case

case
maxiter -= 128;
if (max_iter < 128) max_iter = 128;
printf("max iter: %d\n", max_iter); break;
saturation = 1 - saturation; break;

;
;
!

screen_dump(); return; maxiter =


4096; break; max_iter = 128;
break; invert = [invert;

s':

case
case z':
case x':
case 1 ':

>

set_texture();

;>

Jvoid hsv_to_rgb(int hue, int min, int max, rgb_t *p)


!{
I
if (min == max) max = min + l;
!
if (invert) hue = max - (hue - min);
!
if ([saturation) {

p~>r = p~>g = p~>b = 255 * (max - hue) / (max - min);


;
return;
:

>

double h

I#

define

double c = VAL * saturation;


double X = c * (1 - fabs(fmod(h,

p~>r = p->g = p->b

= fmod(color_rotate

+le-4

+ 4.0

* (hue - min) / (max - min), 6);

VAL 255

switch((int)h) {
case 0: p~>r =
case 1: p~>r =
case 2: P->g =
case 3: P->g =
case 4: p->r =
default: : p->r =

2) - 1));

= 0;

c; p->g
x; p->g
c; p->b
x; p->b
x; p->b
c; p->b

=
=
=
=
=
=

x; return.
c; return
x; return
c; return
c; return

x;

:>

Jvoid calc_mandel()
;{
!
int i, j, iter,
min, max;

rgb_t *px;
;
double x, y, zx, zy, zx2,
zy2;
;
min = max_iter;
max = 0;
!
for (i = 0; i <
height; i++)
{
:
px = tex[i];
!
y = (i - height/2) * scale + cy;

for ( j = 0; j < width; j++, px++) {


;
x = (j - width/2) * scale + cx;
;
iter = 0;
|
!
!

zx = hypot(x
- .25,
if (x < zx - 2 * zx
if ((x + l)*(x + 1)

y);
* zx +
+y*y

;
|
|
!
!
|

zx = zy = zx2 = zy2
= 0;
for (; iter < max_iter && zx2 + zy2 < 4; iter++) {
zy = 2 *
zx * zy
+ y;
zx = zx2 - zy2 + x;
zx2 = zx * zx;
zy2 = zy * zy;

.25) iter =maxiter;


<1/16) iter
maxiter;

>

!
!
!

if (iter < min) min


= iter;
if (iter > max) max
= iter;
*(unsigned short *)px
= iter;

>

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

20/78

19/11/2015

M andel brot set - Rosetta Code

i>
for (i = 0; i < height; i++)
for (j = 0, px = tex[i]; j < width; j++, px++)
hsv_to_rgb(*(unsigned short*)px, min, max, px);

Jvoid alloc_tex()

;{
!

int

i, ow = tex_w, oh

tex_h;

;
;

for
for

(tex_w = 1; tex_w
(tex_h = 1; tex_h

<
<

width; tex_w
height; tex_h

= 1);
= 1);

if (tex_h 1= oh || texw != ow)


tex = realloc(tex, tex_h * tex_w * 3 + tex_h * sizeof(rgb_t*));

for (tex[0] = (rgbt *)(tex + tex_h), i = 1; i < texh; i++) tex[i] = tex[i - 1] +
tex_w;

void set_texture()
\{

\
|

alloc_tex();
calc_mandel();
glEnable(GL_TEXTURE_2D); glBindTextureCGL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h, 0, GL_RGB,
GL_UNSIGNED_BYTE, tex[0]);

I
!
!

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);


glTexParameteri(GL_TEXTURE_2D, GLTEXTUREMAGFILTER, GL_NEAREST);
render();

;>

Jvoid mouseclick(int button, int state, int x, int y)


\i
!
if
(state != GLUT_UP)
return;
j
;

cx
cy

+= (x -= (y -

width /
height/

2) * scale;
2) * scale;

switch button {
case GLUT_LEFT_BUTTON: /* zoom in */
if (scale > fabs(x) * le-16 && scale > fabs(y) * le-16) scale /= 2;
break;
case GLUT_RIGHT_BUTTON: /* zoom out */ scale *= 2; break;
/* any other button recenters */
}

set_texture();

void resize(int w, int h)


;{
|
printf("resize %d %d\nM, w,
|
width = w;
!
height = h;
!
;

glViewport(0, 0, w, h);
glOrtho(0, w, 0, h, -1, 1);

set_texture();

h);

j}
void init_gfx(int *c, char **v)
;{
;
glutlnit(c, v);
I
glutlnitDisplayMode GLUTRGB ;
I
glutlnitWindowSize 640, 480);
!
glutDisplayFunc(render);

gwin = glutCreateWindowC'Mandelbrot");

glutKeyboardFunc(keypress);
glutMouseFunc(mouseclick);
glutReshapeFunc(resize);
glGenTextures(l, &texture);
set_texture();

!
!

j>
Jint main(int c, char **v)
;{
|
init_gfx(&c, v);
;
printf("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t"
;
"<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n");

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

21/78

19/11/2015

M andel brat set - Rosetta Code

glutMainLoopQ;
return 0;

C++
This generic function assumes that the image can be accessed like a two-dimensional array of colors. It may be passed a true array (in which case
the Mandelbrot set will simply be drawn into that array, which then might be saved as image file), or a class which maps the subscript operator to
the pixel drawing routine of some graphics library. In the latter case, there must be functions get first dimension and get second dimension defined
for that type, to be found by argument dependent lookup. The code provides those functions for built-in arrays.
tfincLude <cstdLib> finclude <compiex>

[// get dimensions for arrays


!template<typename ElementType, std::size_t diml, std::size_t dim2> ! std::size_t get_first_dimensioni ElementType C&a)[diml][dim2])
;{
return diml;

;}
ftemplatectypename ElementType, std::size_t diml, std::size_t dim2> ! std::size_t get_second_dimension(ElementType (&a)[diml][dim2])

|{
return dim2;

i> template<typename ColorType, typename ImageType>


void draw_Mandelbrot ImageTypefi image,
//where to draw the image
ColorType setcolor, ColorType non_set_color,
//which colors to use for set/non-set points
double cxmin, double cxmax, double cymin, double cymax,//t/ie red to draw in the complex plane unsigned int
max_iterationsl
//the maximum number of iterations

t
std::size_t const ixsize = get_first_dimensionl;image); std::size_t
const iysize = get_first_dimension(image); for (std::size_t ix = 0; ix <
ixsize; ++ix) for (std::size_t iy = 0; iy < iysize; ++iy)

{
std::complex<double> c(cxmin + ix/(ixsize-1.0)*(cxmax-cxmin), cymin + iy/(iysize-1.0)*(cymax-cymin)); std::complex<double> z =
0; unsigned int iterations;
for (iterations = 0; iterations < max_iterations && std::abs(z) < 2,0; ++iterations) z = z*z + c;
image[ix][iy] = (iterations == max_iterations) ? set_color : non_set_color;

}
>

Note this code has not been executed.

c#
using System;
;using System.Drawing;
;using System.Drawing.Imaging;
Jusing System.Threading;
!using System.Windows.Forms;
'/// <summary>
'/// Generates bitmap of Mandelbrot Set and display it on the form.
[/// </summary>
[public class MandelbrotSetForm : Form
;{
! const double MaxValueExtent = 2.0;
!
Thread thread;
;

static

double CalcMandelbrotSetColor ComplexNumber c)

:{
|
!

// from http://en. wikipedia. org/w/index.php?title=Mandelbrot_set


const int Maxlterations = 1000;
const double MaxNorm = MaxValueExtent * MaxValueExtent;

;
[
!

int iteration = 0;
ComplexNumber z = new ComplexNumber );
do

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

22/78

19/11/2015

M andel brat set - Rosetta Code

z = z * z + c; iteration++;
} while (z.Norm() < MaxNorm && iteration < Maxlterations); if (iteration < Maxlterations)
return (double)iteration / Maxlterations;
else
return 0; // black

static void GenerateBitmapfBitmap bitmap)

double scale = 2 * MaxValueExtent / Math.Min(bitmap.Width, bitmap.Height); for (int i = 0; i


< bitmap.Height; i++)
{
double y = (bitmap.Height / 2 - i) * scale; for (int j = 0; j <
bitmap.Width; j++)

{
double x = ( j - bitmap.Width / 2) * scale;
double color = CalcMandelbrotSetColor(new ComplexNumber(x, y)); bitmap. Set
Pixel (j,, i, GetColor color));
>
>
>

static Color GetColor(double value)

{
const double MaxColor = 256; const double ContrastValue = 0.2; return Color.FromArgb(0, 0,
(int)(MaxColor * Math.Pow(value, ContrastValue)));
}
public MandelbrotSetForm()

{
// form creation
this.Text = "Mandelbrot Set Drawing"; this.BackColor = System.Drawing.Color.Black;
this.BackgroundlmageLayout = System.Windows.Forms.imageLayout.Stretch;
this.MaximizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen; this.FormBorderStyle =
FormBorderStyle.FixedDialog; this.ClientSize = new Size(640, 640);
this.Load += new System.EventHandler(this.MainForm_Load);
}
void MainForm_Load(object sender, EventArgs e)

{
thread = new Thread(thread_Proc); thread.IsBackground = true; thread.Start(this.ClientSize);
}
void thread_Proc(object args)

{
// start from small image to provide instant display for user Size size = (Size)args; int width =
16;
while (width * 2 < size.Width)
{
int height = width * size.Height / size.Width;
Bitmap bitmap = new Bitmap width, height, PixelFormat.Format24bppRgb);
GenerateBitmap(bitmap);
this.BeginInvoke(new SetNewBitmapDelegate SetNewBitmap), bitmap); width *= 2;
Thread.Sleep(200);
>

// then generate final image


Bitmap finalBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb);
GenerateBitmap(finalBitmap);
this.BeginInvoke(new SetNewBitmapDelegate SetNewBitmap), finalBitmap);

void SetNewBitmapiBitmap image!

{
if (this.Backgroundlmage != null) this.Backgroundlmage.Dispose(); this.Backgroundlmage = image;
}
delegate void SetNewBitmapDelegate Bitmap image);
static void Main()

{
Application.Run(new MandelbrotSetForm());
}

struct ComplexNumber
{
public double Re; public double Im;
public ComplexNumber(double re, double im)

{
this.Re = re; this.Im = im;
}
public static ComplexNumber operator + ComplexNumber x, ComplexNumber y)

{
return new ComplexNumber x.Re + y.Re, x.Im + y.Im);
}
public static ComplexNumber operator * ComplexNumber x, ComplexNumber y)

{
return new ComplexNumber x.Re * y.Re - x.Im * y.Im, x.Re *
y.Im + x.Im * y.Re);
}
public double NormQ

{
http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

23/78

19/11/2015

M andel brat set - Rosetta Code

return Re * Re + Im * Im;

Clojure
Translation of: Perl (ns mandelbrot
(:refer-clojure :exclude [+ * <])
(:use (clojure.contrib complex-numbers)
(clojure.contrib.generic [arithmetic :only [+ *]] [comparison :only [<]]
math-functions :only [abs]])))
defn mandelbrot? [z]
(loop [c 1
m (iterate #(+ z (* % %)) 0)]
(if (and (> 20 c)
(< (abs (first m)) 2) )
(recur (inc c)
(rest m))
(if (= 20 c) true false))))
(defn mandelbrot []
(for [y (range 1 -1 -0.05)
x (range -2 0.5 0.0315)]
(if (mandelbrot? (complex x y)) "# ....................... )))
(println (interpose \newline (map # apply str %) (partition 80 (mandelbrot)))))

D
Textual Version
This uses std. complex because D built-in complex numbers are deprecated.
Jvoid main() {
! import std.stdio, std.complex;

for (real y = -1.2; y < 1.2; y += 0.05) {


for (real x = -2.05; x < 0.55; x += 0.03) {
auto
z= 0.complex;

!
I
;
;

foreach (_; 0 .. 100)

z = z AA 2 + complex x, y);
write(z.abs < 2 ? '#' : '.');

i
!

>

writeln;

i>
!>

Output:
. . .##.. .
######..
#######

.######,

.######,

http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

24/78

19/11/2015

M andel brot set - Rosetta Code


#######.

######.
. . .##.. .

More Functional Textual Version


The output is similar.
void main() {
; import std.stdio, std.complex, std.range, std.algorithm;
! foreach (immutable y; iota(-1.2, 1.2, 0.05))
!
iota(~2.05, 0.55, 0.03).map!(x => .complex
I
.recurrence! ((a, n) => a[n - 1] AA 2 + complex(x, y))

.drop(iee).front.abs < 2 ? '#' : .1).writeln;


;}

Graphical Version
Library: QD
Library: SDL
Library: Phobos
[import qd;

[double lensqr(cdouble c) { return c.re * c.re + c.im * c.im; }

[const Limit = 150;


[void main() {
[ screen(640, 480);
I for (int y = 0; y < screen.h; ++y) {
[ flip; events;
! for (int x = 0; x < screen.w; ++x) {
j
auto
;
c_x = x
* 1.0 / screen.w !
c_y = y
* 1.0 / screen.h [
c = c_y
* 2.0i + c_x * 3.0
[
z = 0.0i + 0.0,
I
i=0;
;
for (; i < Limit; ++i) {
;
z=z*
z + c;
[
if (lensqr(z) >
4) break;

!
j
[
!
[
'
;
;
[
[
[
!
;
;
[

0.5,
0.5,
- 1.0,

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

25/78

19/11/2015

M andel brat set - Rosetta Code

>

auto value = cast(ubyte) (i * 255.0 / Limit); pset x, y,


rgb value, value, value));

)
}
while (true) { flip; events; )

Dart
Implementation in Google Dart works on http://try.dartlang.org/ (as of 10/18/2011) since the language is very new, it may break in the future. The implementation
uses a incomplete Complex class supporting operator overloading.
[class Complex {
! double _rj_i;
! Complex(this._r,this._i);
! double get r => _r;
; double get i => _i;
; String toString() => "(frjji)";
! Complex operator +(Complex other) => new Complex(r+other.r.,i+other.i); ! Complex operator *(Complex other) =>
!
new Complex(r*other.r~i*other.i,r*other.i+other.r*i);
double abs() => r*r+i*i;
;}
Ivoid main() {
! double start_x=-1.5;
double start_y=-1.0;
; double step_x=0.03;
; double step_y=0.1;
! for(int y=0;y<20;y++) {
!
String line="";
!
for(int x=0;x<70;x++) {
;
Complex c=new Complex(start_x+step_x*x,start_y+step_y*y);
;
Complex z=new Complex(0.0J
0.0);
!
for(int
i=0;i<100;i++) {
:
z=z*(z)+c;
!
if(z.abs()>2) {
I

break;

>

line+=z.abs()>2 ? " :

;>

! print(line);
>
;}

DEC BASIC-PLUS
Works under RSTS/E v7.0 on the simh PDP-11 emulator. For installation procedures for RSTS/E, see here
(http://www.eecis.udel.edu/~mader/delta/downloadrsts.html).
10 X1=59\Y1=21
;20 Il=-1.0\I2=1.0\R1=-2.0\R2=1.0
130 S1=(R2-R1)/X1\S2=(I2-I1)/Y1
140 FOR Y=0 TO Y1
>50 I3=I1+S2*Y
60 FOR X=0 TO XI
70 R3=R1+S1*X\Z1=R3\Z2=I3
[80 FOR N=0 TO 30
190 A=Z1*Z1\B=Z2*Z2
!l00 IF A+B>4.0 THEN GOTO 130
110 Z2=2*Z1*Z2+I3\Z1=A-B+R3
120 NEXT N
130 PRINT STRING$(l%j62%-N);
[140 NEXT X
1150 PRINT
160 NEXT Y
>170 END

Output:
=====<<<;;;;;;:::96032;;;;;===
>===<<;;;;;;;:; :873*079: :;;;;<

http://rosetlacode.org/wiki/M andel brot_sel#M ATLAB

26/78

;;::
:972456-567763
;===<;;;;;;;:
988897735/
:9974 .3
:997564'
;>==<;;;;;;
98888764
:::98758
.>
!===<<<;;;;
;>==<;;;;;;:
>::988897735/
98888764.3
|><;
;;
;9875&
9974
1997564'
>;;;;
!>===<<;;
19/11/2015
;>>==<<<<<<<<<<<<<;j;j::::996.
&2
!>;;;;;::
:972456-567763

=====<
;=;;::::: :999752
;>=;;;:599999999886

;>=;;;:599999999886
;=;;:::::
:999752
;>>==<<<<<<<<<<<<<;j;i::::996. &2

(.9: :::;;<====
*79:;===
%78: ;;==
5789999:
;;<==
+9; ;<=
*9;;;=
45335:;=
8:;;;=
&89:;;;<<<<=
&89:;;;<<= 8:;;;=
*9;;;= +9; ;<= %78:
;;== *79:;===
45335:;==== 5789999:
;;<===== (.9:
:::;;<=======
:::873*079: :;;;;< --------------------;:::96032:;; ;;===========

M andel brat set - Rosetta Code

DWScript
Translation of: D const maxlter = 256;
var x, y, i : Integer;
^or y:=~39 to 39 do begin | for x:=-39 to 39 do begin !
var c := Complex(y/40-0.5, x/40);
!
var z := Complex(0,
0);
I
for i:=1 to maxlter
do begin

z := z*z + c;
;
if Abs(z)>=4 then
Break;
;

end;

!
!

if i>=maxlter then
Print('#')

!
; end;

else Print('.');

; PrintLn(");

Erlang
Translation of: Haskell
Function seqJloat/2 is copied from Andrew Fecheyr's GitHubGist (https://gist.github.com/andruby/241489).
Using module complex from Geoff Hulette's GitHub repository (https://github.com/ghulette/mandelbrot- erlang/blob/master/simple/complex.erl)
Geoff Hulette's GitHub repository (https://github.com/ghulette/mandelbrot-erlang) provides two alternative implementations which are very interesting.

-module(mandelbrot).
-export([test/0]).
magnitude(Z) ->
R = complex:real(Z),
I = complex:imaginary(Z)j R * R
+ I * I.
mandelbrot(A, Maxi, Z, I) ~>
case (I < Maxi) and (magnitude(Z) < 2.0) of true ->
NZ = complex:add(complex:mult(Z, Z), A),
mandelbrot(A, Maxi, NZ, I + 1); false ->
case I of Maxi ->
$*;
_ ->
$

end
end.

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

27/78

19/11/2015

M andel brat set - Rosetta Code

!test() ->
!
lists:map(

fun(S) ->io:format("~s",[S]) end,


:
[
:
[
;
begin
!
Z = complex:make(X, Y),

mandelbrot Z, 50, Z, 1)
;
end
\
|| X
<- seq_float(-2,
0.5, 0.0315)
!
] ++
"\n"
I
|| Y<- seq_float
-1,1, 0.05)
!
] ),

ok.
%

**************************************************

**************************************************

Cop ied from https://gist.github.com/andruby/241489

seq_float(Min, Max, Inc, Counter, Acc) when (Counter*Inc + Min) >= Max -> ;
lists:reverse([Max|Acc]);
;seq_floatiMin, Max, Inc, Counter, Acc) ->
; seq_float(Min, Max, Inc, Counter+1, [Inc * Counter + Min|Acc]).
Jseq float Min, Max, Inc) ->
I seq_float(Min, Max, Inc, 0, [ ] ) .
\%

**************************************************

Output:

**

******
******

*###****

*** *****************
****************************
******************************
******************************
************************************ *
**********************************
** ***** *
**********************************
***********
************************************
************** ************************************
*****************************************************
*****************************************************
*****************************************************
***************************************************
***********
*

************************************
**********************************

************************************
******************************

****************************
************************ *** ***
*****************
******** ** *
******

********

**

ERRE
PROGRAM
MANDELBROT !$KEY
!$INCLUDE="PC.LIB"
BEGIN

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

28/78

19/11/2015

M andel brot set - Rosetta Code

;SCREEN(7)
[GR_WINDOW(-2,1,5,2, -1.5)
IFOR X0=-2 TO 2 STEP 0.01 DO I
Y0=-1.5 TO 1.5 STEP 0.01 DO
|
X=0
|
Y=0

FOR

I
I

ITERATION=0
MAX_ITERATI0N=223

|
;
!

WHILE (X*X+Y*Y<=(2*2) AND ITERATION<MAX_ITERATION) DO


X_T EMP =X*X-Y*Y+X0
Y=2*X*Y+Y0

X=X_TEMP

j
;

ITERATI0N=ITERATI0N+1
END WHILE

i
I

IF ITERATION<>MAX_ITERATION THEN
C=ITERATION
ELSE
C=0
END IF

I
|
|

I
PSET(X0,Y0,C)
I
END FOR
lEND FOR ! END
PROGRAM

Note: This is a PC version which uses EGA 16-color 320x200. Graphic commands are taken from PC.LIB library.

F#
open System. Drawing open
System.Windows.Forms ftype
Complex =

{
re : float; im ;
float
}
let cplus (x:Complex) (y:Complex) : Complex =

{
re = x.re + y.re; im =
x.im + y.im
let cmult (x:Complex') (y:Complex) : Complex =

{
re
im

- x.re
= x.re

* y.re - x.im
* y.im + x.im

*
*

y.im;
y.re;

}
let norm (x:Complex) : float =
x.re*x.re + x.im*x.im
ftype Mandel = class
inherit Form
static
member xPixels = 500
static
member yPixels = 500
val mutable bmp : Bitmap
member x.mandelbrot xMin xMax yMin yMax maxlter = let rec
mandelbrotlterator z c n = if (norm z) > 2.0 then false
else match n with | 0 -> true
| n ~> let z' = cplus ( cmult z z ) c in
mandelbrotlterator z c (n-1) (xMax - xMin) / (float
let dx let (Mandel.xPixels)) yMax - yMin) / (float
dy
(Mandel.yPixels))
for xi = 0 to Mandel.xPixels-1 do
for yi = 0 to Mandel.yPixels-1 do
let c = {re = xMin + (dx * float(xi) ) ;
im = yMin + (dy * float(yi) )> in if (mandelbrotlterator
{re=0.;im=3.;> c maxlter) then x.bmp.SetPixel(xi,yi,Color.Azure)
else
x.bmp.SetPixel(xi,yi,Color.Black)
done
done
member public x.generate () = x.mandelbrot (-1.5) 0.5 (-1.0) 1.0 200 ; x.Refresh()
new() as x = {bmp = new Bitmap(Mandel.xPixels , Mandel.yPixels)} then x.Text <"Mandelbrot set" ;

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

29/78

19/11/2015

M andel brat set - Rosetta Code

x.Width <~ Mandel.xPixels ; x.Height


<- Mandel.yPixels ;
x.Backgroundlmage <- x.bmp;
x.generate(); x.Show ;

Ilet f = new Mandel{) nio Application.Run(f)

Forth
This uses grayscale image utilities.
600 value max-iter
mandel ( gmp F: imin imax rmin rmax -- )
; 0e 0e { F: imin F: imax F: rmin F: rmax F: Zr F: Zi }
! dup bheight 0 do
! i s>f dup bheight s>f f/ imax imin f- f* imin f+ TO Zi ! dup bwidth 0 do
;
i s>f
dup bwidth s>f f/rmaxrmin f- f* rmin f+ TO Zr
;
Zr Zi
max-iter
;
begin
1- dup
!
while
fover fdup f* fover fdup f*
!
fover fover f+ 4e f<

while
f- Zr f+
;
frot frot f* 2e f* Zi f+
;
repeat fdrop fdrop
!
drop 0
\ for a pretty grayscale image, replace with: 255 max-iter */
!
else
drop 255
!
then
fdrop fdrop
!
over i
j rot g!
> loop ; loop drop ;
!80 24 graymap
Idup -le le -2e le mandel
Idup gshow

jfree bye

Fortran
Works with: Fortran version 90 and later program mandelbrot
selected_real_kind (9, 99)

implicit none
integer ,
parameter

: rk

integer ,
integer ,

parameter
parameter

: i_max
: j_max

integer ,
real (rk).
real (rk).
real (rk).
real (rk).
real (rk).

parameter
parameter
parameter
parameter
parameter
parameter

: n_max
: x_centre
: y_centre
: width
: height
: dx_di

real (rk).
parameter
real (rk).
parameter
real (rk).
parameter
integer, dimension (i
integer
:i
integer
integer
real (rk)
real (rk)

J
:n
:x
:y

real (rk)
real (rk)
real (rk)
real (rk)

:x0
: y_0
: x_sqr
: y_sqr

: dy_dj
: x_offset
: y_offset
max, j_max)

800
600
100
-0.5_rk
0.0_rk
4.0_rk
3.0_rk

width / i_max height / j m a x


x_centre - 0.5_rk * (i_max + 1) y_centre
* dx_di
- 0.5_rk * (j_max + 1) : image
* dy_dj

do j = 1, j_max
y_0 = y_offset + dy_dj * j do i = 1,
imax
x_0 = x_offset + dx_di * i x =
0.0_rk y = 0.0_rk n = 0 do
x_sqr = x ** 2 y_sqr = y ** 2
if (x_sqr + y_sqr > 4.0_rk) then

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

30/78

19/11/2015

M andel brat set - Rosetta Code

image (i, j) = 255 exit


end if
if (n == n_max) then image i, j) = 0
exit end if
y = y_0 + 2.0_rk * x * y x = x_0 +
x_sqr - y_sqr n = n + 1

end
do end do
end do
open (10, file = 'out.pgm')
write (10, '(a/ i0, lx, i0/ i0)) 'P2', i_max, j_max, 255 write (10, (i0)) image
close (10)

end program mandelbrot

GLSL
This example works directly on Shadertoy link[l] (https://www.shadertoy.com/view/XsfGWS) !void main (void)
\i
[
!
I
!
!

vec2 uv = glFragCoord.xy /
float scale = iResolution.y
uv=((uv-0.5)*5.5);
uv.y*=scale;
uv.y+=0.0;
uv.x-=0.5;

iResolution.xy;
/ iResolution.x;

vec2 z = vec2(0.0, 0.0); vec3 c =


vec3(0.0, 0.0, 0.0); float v;

for(int i=0;(i<170);i++)

t
if(((z.x*z.x+z.y*z.y) >= 4.0)) break; z = vec2(z.x*z.x z.y*z.y, 2.0*z.y*z.x) + uv;

if((z.x*z.x+z.y*z.y) >= 2.0)

{
c.b=float(i)/20.0; c.r=
in((float i / 0));
>
> gl_FragColor

= 604(0,1.0);

>

gnuplot

The following script draws an image of the number of iterations it takes to escape the circle with radius rmax with a maximum of nmax.
The output from gnuplot is controlled by setting the appropriate values for the options terminal and output.
set terminal png
set output mandelbrot.png

irmax = 2
;nmax = 100
[complex (x, y) = x * {1, 0} + y * {0, 1}
[mandelbrot (z, z0, n) = n == nmax || abs (z) > rmax ? n : mandelbrot (z ** 2 + z0, z0, n + 1)
|set samples 200
iset isosamples 200
set pm3d map
;set size square
jsplot [-2 : .8] [-1.4 : 1.4] mandelbrot (complex (0, 0), complex (x, y), 0) notitle

Output:

http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

31/78

19/11/2015

Mandelbrot set - Rosetta Code

Go
Text
Prints an 80-char by 41-line depiction.
package main
iimport "fmt"
[import "math/cmplx"
;func mandelbrot(a complexl28) (z complexl28) { ;
0; i < 50; i++ {
|
z = z*z + a
;

>

return

for i :=

;func main() {
; for y := 1.0; y >=
-1.0;
y -= 0.05
{
1
for x := -2.0;
x<= 0.5;
x +=0.0315 {
!
if cmplx.Abs(mandelbrot(complex(x,
!
|
;

y))) < 2 {

fmt.Print("*")
} else {
fmt.Print(" ")

!
;

>

fmt.Println("")

>

;}

Graphical
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/cmplx"
"os"

const (
maxEsc = 100
rMin = -2. rMax =
.5 iMin = -1. iMax
= 1. width = 750
red = 230 green
= 235 blue = 255

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

32/78

19/11/2015

Mandelbrot set - Rosetta Code

[func mandelbrot(a complexl28) float64 {


I i := 0
! for z := a; cmplx.Abs(z) < 2 && i < maxEsc; i++ {
!
z = z*z + a
>

; return float64(maxEsc-i) / maxEsc func main() {


scale := width / (rMax - rMin) height := int(scale * (iMax
- iMin)) bounds := image.Rect(0, 0, width, height) b :=
image.NewNRGBA(bounds)
draw.Draw(b, bounds, image.NewUniform(color.Black), image.ZP, draw.Src) for x := 0; x <
width; x++ {
for y := 0; y < height; y++ { fEsc := mandelbrot(complex(
float64(x)/scale+rMin, float64(y)/scale+iMin)) b.Set(x, y,
color.NRGBA{uint8(red * fEsc),
uint8(green * fEsc), uint8(blue * fEsc), 255})

}
}
f, err := os.Create("mandelbrot.png") if err != nil {
fmt.Println(err) return

}
if err = png.Encode(f, b); err != nil { fmt.Println(err)

}
if err = f.Close(); err != nil { fmt.Println(err)
>

Haskell
Translation of: Ruby [import Data.Complex
[mandelbrot a = iterate (\z -> zA2 + a) 0 11 50
Imain = mapM_ putStrLn [[if magnitude (mandelbrot (x :+
:
| y <- [1, 0.95 .. -1]]

y)) < 2 then else ' ' j

| x <- [-2, -1.9685 .. 0.5]]

Save the code to file m.hs and run : runhaskell m.hs

Haxe
This version compiles for flash version 9 or greater. The compilation command is

haxe -

swf mandelbrot.swf -main Mandelbrot class Mandelbrot extends flash.display.Sprite

{
inline static var MAXITER = 255;
public static function main() {
var w = flash.Lib.current.stage.stageWidth; var h =
flash.Lib.current.stage.stageHeight; var mandelbrot = new
Mandelbrot(w, h);
flash.Lib.current.stage.addChild(mandelbrot);
mandelbrot.drawMandelbrot();

}
var image:flash.display.BitmapData; public function new(width, height) { super/);
var bitmap:flash.display.Bitmap;
image = new flash.display.BitmapData(width, height, false); bitmap = new
flash.display.Bitmap(image); this.addChild(bitmap);

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

33/78

19/11/2015

M andel brat set - Rosetta Code

public function drawMandelbrot() { image.lock();


var step_x = 3.0 / (image.width-1); var step_y =
2.0 / (image.height-1); for (i in 0...image.height) {
var ci = i * step_y - 1.0; for (j in 0...image.width)
{ var k = 0; var zr = 0.0; var zi = 0.0;
var cr = j * stepx - 2.0;
while (k <= MAXITER && (zr*zr + zi*zi) <= 4) { var temp = zr*zr
- zi*zi + cr; zi = 2*zr*zi + ci; zr = temp; k ++;
>

paint(j, ij k);

}
>

image.unlock/);

inline function paint(x, y, iter) {


var color = iter > MAX_ITER? 0 : iter * 0x100;
image.setPixel(Xj y, color);
>

Icon and Unicon


link graphics
procedure main() width :=
750 height := 600
limit := 100
WOpen("size=n1 1 width||'V 11 height) every x:=l to
width & y:=l to height do {
z:=complex(0,0)
c:=complex(2.5*x/width-2.0,(2.0*y/height-l.0)) j:=0
while j<limit & cAbs(z)<2.0 do

{
z := cAdd(cMul(ZjZ)jC) j+:= 1
>

Fg(mColor(j,limit))
DrawPoint(x,y)

}
Writelmage("./mandelbrot.gif")
WDone )
end
procedure mColor(x,limit)
maxcolor := 2A16-1
color := integer(max_color*(real(x)/limit))
return if x=limit then "black"
else c o l o r ) | c o l o r ) | " , 0 " )
end
record complex(r,i)
procedure cAdd(x,y)
return complex(x.r+y.rjX.i+y.i)
end
procedure cMul(x,y)
return complex(x.r*y.r-x.i*y.iJx.r*y.i+x.i*y.r) end
procedure cAbs(x)
return sqrt(x.r*x.r+x.i*x.i)
end

Library: Icon Programming Library


graphics is required
(http://www.cs.arizona.edu/icon/library/src/gprocs/graphics.icn)

http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

34/78

19/11/2015

M andel brat set - Rosetta Code

This example is in need of improvement:


The example is correct; however, Unicon implemented additional graphical features and a better
example may be possible.

IDL
IDL - Interactive Data Language (free implementation: GDL - GNU Data Language http://gnudatalanguage.sourceforge.net)

[PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations
IxPixelstartVec = Lindgen xPixels) * Float(xRange[1]-xRange[]) / $
!
xPixels + xRange[0]
jyPixelstartVec = Lindgem; yPixels) * Float YRANGE[l]-yrange[0])$
[
/ yPixels + yRange[0]
[constArr = Complex( Rebin( xPixelstartVec, xPixels, yPixels),$
!
Rebin Transpose(yPixelstartVec), xPixels, yPixels))
valArr = ComplexArr( xPixels, yPixels)
[res = IntArr( xPixels, yPixels)
lorilndex = Lindgen( Long(xPixels) * yPixels)
;F0R i = 0, iterations- L DO BEGIN ; only one loop needed
[
; calculation for whole array at once
[ valArr = valArrA2 - constArr
! wherein = Where Abs( valArr) LE 4.0d, COMPLEMENT=whereOut)
[ IF wherein[0] EQ -1 THEN BREAK
[

valArr = valArr[ wherein]

constArr = constArr[ wherein]

[ IF whereOut[3] NE -1 THEN BEGIN


[

res[ oriIndex[ whereOut]] = i+1

!
orilndex = oriIndex[ wherein]
| ENDIF
[ENDFOR
[tv, res ; open a window and show the result
JEND

Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200 IEND

from the command line:

GDL>.run mandelbrot

or

|GDL> Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200

Inform 7
Library: Glimmr Drawing Commands by Erik Temple
Works with: Glulx virtual machine
|"Mandelbrot"
?The story headline is "A Non-Interactive Set".
Slnclude Glimmr Drawing Commands by Erik Temple.
;[Q20 fixed-point or floating-point: see definitions below]
!Use floating-point math.
iFinished is a room.
http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

35/78

19/11/2015

M andel brat set - Rosetta Code

jThe graphics-window is a graphics g-window spawned by the main-window.


;The position is g-placeabove.
IWhen play begins:
!
let fl0 be 10 as float;

now min re
is ( -20 as float
) fdiv fl0;
;
now maxre is ( 6 as float )
fdiv fl0;
|
now minim is ( -12 as float
) fdiv fl0;
2
now maxim is ( 12 as float )
fdiv fl0;
2
now max iterations is 100;
S
add color g-Black to the palette;

add color g-Red to the palette;


j
add hex "#FFA500" to the palette;
2
add color g-Yellow to the palette;
;
add color g-Green to the palette;
2
add color g-Blue to the palette;
!
add hex l,#4B0082" to the palette;

add hex "#EE82EE to the palette;


j
open up
the graphics-window.
2Min Re is a number that varies.
!Max Re is a number that varies, tain
Im is a number that varies, taax Im
is a number that varies.
;Max Iterations is a number that varies.
!Min X is a number that varies, taax
X is a number that varies, tain Y is
a number that varies, flax Y is a
number that varies.
JThe palette is a list of numbers that varies.
![vertically mirrored version]
Window-drawing rule for the graphics-window when max im is fneg min im:
|
clear the graphics-window;
;
let
point be { 0, 0 };
;
now min X is 0 as float;
2
now min Y is 0 as float;
S
let
mX be the width of the
graphics-window
minus1;
S
let
mY be the height of thegraphics-window minus 1;
j
now max X is mX as float;
;
now max Y is mY as float;
2
let
L be the column order with max mX;
2
repeat with X running through L:
!
now entry 1 in point is X;

repeat with Y running from 0 to mY / 2:


;
now entry 2 in point is
Y;
2
let
the scaled point be
the complex numbercorresponding to the point;
2
let
V be the Mandelbrot
result for the scaled point;
2
let
C be the color corresponding to
V;
!
if C is 0, next;

draw a rectangle (C)


in
the graphics-window at the point with size 1 by1;
;
now entry 2 in point
is
mY - Y;
2
draw a rectangle (C)
in
the graphics-window at the point with size 1 by1;
2
yield to VM;
2
rule succeeds.
![slower non-mirrored version]
Window-drawing rule for the graphics-window:
;
clear the graphics-window;
2
let
point be { 0, 0 };
2
now min X is 0 as float;
S
now min Y is 0 as float;
!
let
mX be the width of the
graphics-window
minus1;
2
let mY be the height of the graphics-window minus 1;
2
now max X is mX as float;
2
now max Y is mY as float;
2
let L be the column order with max mX;
S
repeat with X running through L:
!
now entry 1 in point is X;

repeat with Y running from 0 to mY:


;
now entry 2 in point is
Y;
2
let
the scaled point be
the complex numbercorresponding to the point;
2
let
V be the Mandelbrot
result for the scaled point;
!
let
C be the color corresponding to
V;

if C is 0, next;
j
draw a rectangle (C) in the graphics-window at the point with size 1 by 1;
;
yield to VM;
;
rule succeeds.
ho decide which list of numbers is column order with max (N - number):
S
let L be a list of numbers;
S
let L2 be a list of numbers;
>
let D be 64;
;
let rev be false;
2
while D > 0:
;
let X be 0;
S
truncate L2 to 9 entries;
!
while X <= N:
http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

36/78

19/11/2015

2
;
;
!
S
!
;
;
2

if D is
64
increase X
if rev is true:
reverse L2;
let rev
be
otherwise:
let rev
be
add L2 to L;
let D be D / 2;
decide on L.

M andel brat set - Rosetta Code


or X / D is odd, add X to L2;
by D;

false;
true;

ho decide which list of numbers is complex number corresponding to (P - list of numbers):

let R be a list
of numbers;
;
extend R
to 2 entries;
;
let X be
entry 1 in P as float;
;
let X be
(max re fsub min re)
fmul (X fdiv max X);
2
let X be
X fadd min re;
!
let Y be
entry 2 in P as float;

let Y be
(max im fsub min im)
fmul (Y fdiv max Y);
;
let Y be
Y fadd min im;
;
now entry 1
inR is X;
2
now entry 2
inR is Y;
2
decide on R.
ho decide which number is Mandelbrot result for (P - list of numbers):
;
let c_re
be entry 1 in P;
;
let c_im
be entry 2 in P;
2
let z_re
be 0 as float;
2
let z_im
be z_re;
!
let threshold
be 4 as float;

let
runs be 0;
2
while 1 is 1:
1
[z
=z* z]
2
let
r2be
z_refmul z_re;
2
let
i2be
z_imfmulz_im;
!
let
ribe
z_refmul z_im;

let
z_re be
r2 fsub i2;
>
let
z_imbe ri fadd ri;
1
[z
=z+c ]
2
let
z_re be
z_re fadd c_re;
2
let
z_imbe z_im fadd c_im;
!
let norm be (z_re fmul z_re) fadd (z_im fmul z_im);
!
increase runs by 1;
2
if norm is greater than threshold, decide on runs;
;
if runs is max iterations, decide on 0.
ho decide which number is color corresponding to (V - number):
S
let L be the number of entries in the palette;
:
let N be the remainder after dividing V by L;
;
decide on entry (N + 1) in the palette.
JSection - Fractional numbers (for Glulx only)
ho decide which number is (N - number) as float: (- (numtof({N})) -).
ho decide which number is (N - number)fadd (M
- number): (- (fadd({N>,
To decide which number is (N - number)fsub (M
- number): (- (fsub({N),
;To decide which number is (N - number)fmul (M
- number): (- (fmul({N),
JTo decide which number is (N - number) fdiv (M
- number): (- (fdiv({N),
ho decide which number is fneg (N - number): (- (fneg({N})) -). fTo yield to
VM: (- glk_select_poll(gg_event); -).

(M)))
{M}))
{M}))
{M}))

-).
-).
-).
-).

jllse Q20 fixed-point math translates as (- Constant Q20_MATH; -).


;Use floating-point math translates as (- Constant FL0AT_MATH; -).
Slnclude (- frifdef
Q20_MATH;
h Q11.20 format: 1 sign
bit,
11 integer bits, 20 fraction bits
;[ numtof n r; @shiftl n
20 r; return r; ];
;[ fadd n m; return n+m; ];
![ fsub n m; return n-m; ];
![ fmul n m; n = n + $$1000000000; @sshiftr n 10 n; m = m + $$1000000000; @sshiftr m 10 m; return n * m; ]; ![ fdiv n m;
@sshiftr m 20 m; return n / m; ];
[ fneg n; return -n; ];
>#endif;
2#ifdef FLOAT_MATH;
![ numtof f; @"S2:400" f f; return f; ];
![ fadd n m; @"53:416" n m n;
![ fsub n m; @"53:417" n m n;

return n; ];
return n; ];

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

37/78

19/11/2015

M andel brat set - Rosetta Code

![ fmul n m; @"S3:418" n m n; return n; ];


![ fdiv n m; @"S3:419" n m n; return n; ];
![ fneg n; (Sbitxor n $80000000 n; return n; ]; I#endif;
:-)

Newer Glulx interpreters provide 32-bit floating-point operations, but this solution also supports fixed-point math which is more widely
supported and accurate enough for a zoomed-out view. Inform 6 inclusions are used for the low-level math functions in either case. The
rendering process is extremely slow, since the graphics system is not optimized for pixel-by-pixel drawing, so this solution includes an
optimization for vertical symmetry (as in the default view) and also includes extra logic to draw the lines in a more immediately useful order.

Mandelbrot

A Non-Interactive Set
Release 1/Serial number 101117/Inform 7 build 6F95 (I6M.31 lib 6/12N) SD
Finished

The characteristic function of the Mandelbrot can be defined as follows:


mcf=. (<: 2:)@|@(] ((*:@] + [) A :((<: 2:)@|@]) A :1000) 0:) NB. 1000 iterations test

The Mandelbrot set can be drawn as follows:


jdomain=. |.0| :({.[ + ] j./&i.&>/@+.@(ljl + ] % ------------------------------ /(?[))&>/
;load'graph'
[viewmat mcf "0 (a) domain (_2j_l l jl) ; 0.01 NB. CompLex interval, and resolution

A smaller version, based on a black&white implementation of viewmat (and paraphrased, from html markup to wiki markup), is shown
here:
viewmat mcf "0 (8 domain (_2j_l ljl) ; 0.1 NB. CompLex interval and resolution

The output is HTML-heavy and can be found here (split out to make editing this page easier).

Java
Library: Swing Library: AWT
[import java. awt.Graphics;
[import java.awt.image.Bufferedlmage;
[import javax. swing. J Frame;
public class Mandelbrot extends IFrame {

\
\
\

private final int MAXITER = 570; private


final double ZOOM = 150; private
Bufferedlmage I; private double zx, zy, cX,
http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

38/78

19/11/2015

M andel brat set - Rosetta Code

cY, tmp;
public MandelbrotQ {
super("Mandelbrot Set"); setBounds(100, 100,,
800, 600); setResizable(false);
setDefauItCloseOperation(EXIT_ON_CLOS E);
I = new Bufferedlmageigetwidth , getHeight , Bufferedlmage.TYPE_lNT_RGB); for (int y =
0; y < getHeight ); y++) { for (int x = 0; x < getwidth(); x++) { zx = zy = 0; cX = (x - 40 0) /
ZOOM; cY = (y - 300) / ZOOM; int iter = MAXITER;
while (zx * zx + zy * zy < 4 && iter > 0) { tmp = zx * zx
- zy * zy + cX; zy = 2.0 * zx * zy + cY; zx = tmp;
iter--;
>

I.setRGB x, y, iter | (iter 8));


}
>
>

^Override
public void paint(Graphics g) {
g,drawlmage(l, 0, 0, this);
>

public static void main(String[] args) {


new MandelbrotQ.setvisible(true);
}

JavaScript
Works with: Firefox version 3.5.11
This needs the canvas tag of HTML 5 (it will not run on IE8 and lower or old browsers).
The code can be run directly from the Javascript console in modem browsers by copying and pasting it.
[function mandellter(cx, cy, maxlter) {
! var x = 0.0;
! var y = 0.0;
!
var xx = 0;
!
var yy = 0;
;
var xy = 0;
; var i = maxlter;
I while (i-- && xx + yy <= 4) {
I xy = x * y;

xx = x * x; i yy
= y * y;
;
x = xx - yy +cx;
;
y = xy + xy +cy;
;>

! return maxlter - i;
;}
[function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) { [ var width =
canvas.width;
! var height = canvas.height;
! var ctx = canvas.getContext(12dQ;
; var img = ctx.getImageData(0, 0, width, height);
; var pix = img.data;
I for (var ix =0; ix < width; ++ix) {
! for (var iy =0; iy < height; ++iy) {
!
var x = xmin + (xmax - xmin)
* ix

var y = ymin + (ymax - ymin)


* iy
;
var i =mandellter(x, y, iterations);
|
var ppos = 4 * (width * iy +
ix);

/ (width
/ (height

- 1);
- 1);

! if (i > iterations) {
|
pix ppos = 0;
;
pix ppos + 1] = 0;

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

39/78

19/11/2015

M andel brat set - Rosetta Code

!
j
;

pix[ppos +2] =0;


} else {
var c = 3 * Math.log i / Math.log(iterations - 1.0);

:
!
!
!

if

>

;
:
!
!
|
|
;
!
:

else if ( c
pix[ppos]
pix[ppos
pix[ppos
}
else {
pix[ppos]
pix[ppos
pix[ppos
}

>

pix[ppos

(c < i) {
pix[ppos]
pix[ppos
pix[ppos

+ 3]

= 255 * c;
+1] =0;
+ 2] = 0;
< 2 ){
= 255;
+ 1] = 255 * (c
+ 2] = 0;
= 255;
+ l] = 255;
+ 2] = 255 * (c

-1);

-2);

= 255;

i>
:>

! ctx.putImageData(img, 0, 0);
;>

var canvas = document.createElement('canvas');


[canvas, width = 900;
[canvas, height = 600;
Idocument.body.InsertBefore(canvas, document.body.childNodes[ ]);
;mandelbrot(canvas, -2, 1, -1, 1, 1000);

Output: with default parameters:

jq

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

40/78

19/11/2015

M andel brat set - Rosetta Code

Works with: jq version 1.4


The Mandelbrot function as defined here is similar to the JavaScript implementation but generates SVG. The resulting picture is the same.
Preliminaries
#
SVG STUFF
2 def svg(id; width; height):

| "<svg width='\(width // "100%")1 height=\(height // "100%") 1 1


!
xmlns='http://www.w3.org/2000/svg'>";

id=\(id)'

def pixel(x;y;r;g;b;a):

; "<circle cx='\(x)' cy='\(y)' r-'1' fill='ngb(\(r|floor),\(g|floor),\(b|floor))' />"; J# "UNTIL"


S # As soon as "condition" is true, then emit . and stop:
! def do_until(condition; next):
! def u: if condition then . else (next|u) end;

def Mandeliter( cx; cy; maxiter ):


# [i, x, y, xA2+yA2]
;
[ maxiter, 0.0, 0.0, 0.0 ]
! I do_until( .[0] == 0 or .[3] > 4;
I .[1] as $x | .[2] as $y |
|
($x
$y)
as$xy
!
| ($x * $x) as $xx
;
I ($y * $y) as $yy
:
l [ (.[0] i),
|
($xx - $yy
+ cx),
!
($xy + $ xy
+ cy),
!
($xx+$yy)
1

#
#
#
#

i
x
y
xx+yy

])
| maxiter - .[0];

|# width and height should be specified as the number of pixels.


2# obj { xmin: _, xmax: _, ymin: _, ymax: _ }
Sdef Mandelbrot( obj; width; height; iterations ):
! def pixies:
2 range(0; width) as
$ix
;
| (obj.xmin + ((obj.xmax - obj.xmin) * $ix / (width - 1))) as $x
;
| range(0; height)
as $iy
\ I (obj.ymin + ((obj.ymax - obj.ymin) * $iy / (height - 1))) as $y S | Mandeliter( $x; $y; iterations
) as $i
!
I if $i == iterations then
;
pixel($ix; $iy; 0; 0; 0; 255)
2
else
|
(3
* ($i|log)/((iterations - 1.0)|log)) as $c # redness
1
| if $c < 1 then
!
pixel($ix;$iy; 255*$c; 0; 0; 255)
!
elif $c < 2 then
;
pixel($ix;$iy; 255; 255*($c-l); 0; 255)
2
else
J
pixel($ix;$iy; 255; 255; 255*($c-2); 255)
S
end
S
end;

svg(M mandelbrot"; "100%"; "100%"),


2 pixies,
! "</svg>";

Example:
Mandelbrot( {"xmin": -2, "xmax": 1, "ymin": -1, "ymax":!}; 900; 600; 1000 )

Output: ;$ jq -n -r -f mandelbrot.jq > mandelbrot.svg


2# The output can be viewed in a web browser such as Chrome, Firefox, or Safari.

Julia

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

41/78

19/11/2015

Mandelbrot set - Rosetta Code

Thumbnail of SVG produced


by jq program

function mandelbrot(a)
;
z=0
;
for i=l:50
;
z = zA2 + a
!
end
I
return
z
lend
for y=1.0: -0.05: -1.0 I for x=2.0:0.0315:0.5
!
abs(mandelbrot(complex(x, y))) < 2 ? print("*") : print(" ")
!
end
I
printlnQ
end

LabVIEW
Works with: LabVIEW version 8.0 Full Development Suite

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

42/78

19/11/2015

Mandelbrot set - Rosetta Code

This vi creates an image of the points in the Mandelbrot Set using the simplist algorithm for determining which points are in and which points aren't in the set, and based on that determination uses the "Escape Time Algorithm" to assign a color to each point in the complex plain
where black (0 value) indicates that the point is in the set.
To actually create the image, the user provides start and end points in the complex plain between which the vi raster scans at distance intervals given by the user each of which is given a color using the method described above which is then stored in a 2D array which is finally
ploted using an "intensity graph."

Lang5
d2c(*,*) 2 compress 'c dress ;

# Make a complex number.

iterate(c) [0 0](c) "dup * over +" steps reshape execute ; print_line(*) "#*+-. " split swap subscript ""
join . "\n"
75 iota 45 - 20 / 29 iota
14 - 10 / 'd2c outer

#
#
#

x coordinates
y cordinates
Make complex matrix.

How many iterations?

!l0 'steps set


iterate abs int 5 min 'print_line apply # Compute & print

Lasso
define mandelbrotBailout => 16 [define mandelbrotMaxIterations => 1000
[define mandelbrotIterate(x, y) => {
I
local(cr = #y - 0.5,
!
ci = #x,

http://rosetlacode.org/wi ki/M andelbrotjseWM ATLAB

43/78

19/11/2015

M andel brat set - Rosetta Code

}()
Z1 = 0.0, zr = 0.0,

i = 0,
temp, z r 2 j zi2)

++#i;
#temp = #zr 1 #zi #zr2 = #zr * #zr #zi2 = #zi * #zi
#zi2 + #zr2 > mandelbrotBailout? return #i
#i > mandelbrotMaxIterations? return 0
#zr = #zr2 - #zi2 + #cr #zi = #temp + #temp + #ci
currentCapture->restart

define mandelbrotTest() => { local(x, y =


-39.0)

{
stdoutCXn')

#x = -39.0

{
mandelbrotIterate(#x / 40.0, #y / 40.0) == 0? stdout('*')
| stdout(' ');
++#x
#x <= 39.0?
currentCapture->restart

>0;
++#y
#y <= 39.0?
currentCapture->restart

}()
stdout('\n')

miandelbrotTest

Output:
*
*
*
*
*
***

*****
***
*

*********
***************
*********************
*******************
*******************
***********************
*******************
*******************
*******************
*****************
***************

1 ******************************* * *********************************
***********************************
***************************************
http://rosettacode.Org/wiki/M andel brot_set#M ATLAB

44/78

19/11/2015

Mandelbrot set - Rosetta Code

*********
*

***************
***********************
* ************************* *

http://rosetlacode.org/wi ki/M andelbrotjseWM ATLAB

45/78

19/11/2015

M andel brat set - Rosetta Code

*************************************************
***********************************************
*********************************************
*********************************************
***********************************************
***********************************************
*************************************************
*************************************************
***************************************************
***************************************************
***** *************************************************** *****
****** *************************************************** ******
******* *************************************************** *******
********* *************************************************** *********
***** *************************************************** *****
***************************************************
***************************************************
***************************************************
*************************************************
*************************************************
***************************************************
***********************************************
*******************************************
*****************************************
*********************************************
***********
***********
** *****
***** **
*** **************** **************** ***

Logo
Works with: UCB Logo
Sto mandelbrot :left : bottom :side :size ! cs
setpensize [1 1]
make "inc :side/:size ; make "zr :left
2 repeat
:size [
2
make
"zr :zr +:inc
S make
"zi :bottom
j Pu
2 setxy repcount - :size/2 minus :size/2 ; pd
2 repeat :size [
2
make "zi :zi + :inc
S setpencolor count.color calc :zr :zi

fd 1 ] ]
;end
Jto count.color :count
;op (list
: count :count
if :count
> 256[op 0]
if :count
> 128[op 7]
if :count
>
64[op 5]
if :count
>
32[op 6]
if :count
>
16[op 4]
if :count
>
8[op 2]
ifend
:count
>
4[op 1]
op 3

:count)
black
white

magenta
yellow
3red
3green
3blue
3cyan
3
3

2to calc :zr :zi [:count 0] [:az 0] [:bz 0]


2 if :az*:az + :bz*:bz > 4 [op :count]
! if :count > 256 [op :count]
! op (calc :zr :zi (:count + l) (:zr + :az*:az - :bz*:bz) (:zi + 2*:az*:bz)) ;end
mandelbrot -2 -1.25 2.5 400

Mathematica / Wolfram Language


The implementation could be better. But this is a start...

http://rosettacode.Org/wiki/M andel brot_set#M ATLAB

46/78

19/11/2015

M andel brat set - Rosetta Code

I ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1

IeTime[z0_, maxlter_lnteger: 100] := (Length@NestWhileList[(# + z0) A2 &, 0, (Abs@# <= 2) &, 1, maxlter]) - 1
DistributeDefinitions[eTime];
mesh = ParallelTable[eTime[(x + I*y), 1000], {y, 1.2, -1.2, -0.01}, {x, -1.72, 1, 0.01}];
;ReliefPlot[mesh, Frame -> False]

Faster version: |cf = With[{


; mandel = Block[{z = #, c = #},
!
Catch@Do[If[Abs[z] > 2, Throw(3i]; z = zA2 + c, {i, 100}]] &

: },
! Compile[{},Table[mandel[y + x I], {x, -1, 1, 0.005}, {y, -2, 0.5, 0.005}]]

i
;ArrayPlot[cf []]

Mathmap
filter mandelbrot (gradient coloration) ;
c=ri:(xy/xy:[X,X]*1.5-xy:[0.5,0]);
!
z=ri:[0,0]; # initial value z0 = 0
!
# iteration of z
! iter=0;
; while abs(z)<2 && iter<31 ; do
!
z=z*z+c; # z(n+l) = fc(zn)
!
iter=iter+l
! end;
I coloration(iter/32) # color of pixel

MATLAB
This solution uses the escape time algorithm to determine the coloring of the coordinates on the complex plane. The code can be reduced to a single
line via vectorization after the Escape Time Algorithm function definition, but the code becomes unnecessarily obfuscated. Also, this code uses a lot
of memory. You will need a computer with a lot of memory to compute the set with high resolution.
function [theSet,realAxis,imaginaryAxis] = mandelbrotSet [start,gridspacing,last,maxlteration)
; XDefine the escape time algorithm
\ function escapeTime = escapeTimeAlgorithm(z0)
!
j

escapeTime = 0;
z = 0;

;
;
!
!

while (abs(z)<=2) && (escapeTime < maxlteration) )


z = (z + z0)A2;
escapeTime = escapeTime + 1;
end

; end
| XDefine the imaginary axis
! imaginaryAxis = (imag(start):imag(gridSpacing):imag(last));
I
;

XDefine the real axis


realAxis = (real(start):real(gridSpacing):real(last));

\ XConstruct the complex plane from the real and imaginary axes
! complexPlane = meshgridfrealAxis,imaginaryAxis) + meshgrid(imaginaryAxis(end:-1:1),realAxis)'.*i;
! XApply the escape time algorithm to each point in the complex plane theSet = arrayfun
(SescapeTimeAlgorithm, complexPlane);

%Draw the set


pcolor(realAxis,imaginaryAxis,theSet); shading flat;

To use this function you must specify the:


1.
2.

lower left hand comer of the complex plane from which to start the image,
the grid spacing in both the imaginary and real directions,

http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

47/78

19/11/2015

3.
4.

M andel brat set - Rosetta Code

the upper right hand comer of the complex plane at which to end the image and
the maximum iterations for the escape time algorithm.

For example:
1. Lower Left Comer:-2.05-1.2i
2. Grid Spacing: 0.004+0.0004i
3. Upper Right Comer: 0.45+1.2i
4. Maximum Iterations: 500
Sample usage: piandelbrotSet(-2.05-1.2i,0.004+0.00041,0.45+1.2i,500);

Modula-3
MODULE Mandelbrot EXPORTS Main;
IMPORT Wr, Stdio, Fmt, Word;
ICONST m = 50;
I limit2 = 4.0;
TYPE UByte = BITS 8 FOR [0..16_FF];
VAR width := 200;
I
height := 200;
I
bitnum: CARDINAL := 0;
>
byteacc: UByte := 0;

isOverLimit: BOOLEAN;
I Zr, Zi, Cr, Ci, Tr, Ti: REAL;
IBEGIN
; Wr.PutText(Stdio.stdout, ,,P4\n" & Fmt.Int(width) & " " & Fmt.lnt(height) & "\n");

FOR y := 0 TO height - 1 DO
I FOR x := 0 TO width - 1 DO I
Zr
:= 0.0; Zi := 0.0;
I
Cr := 2.0 * FLOAT(x) / FLOAT(width) - 1.5;
;
Ci := 2.0 * FLOAT(y) / FLOAT(height) - 1.0;
;

|
;
I

FOR i := 1 TO m + 1
DO
Tr := Zr*Zr - Zi*Zi + Cr;
Ti := 2.0*Zr*Zi + Ci;
Zr := Tr; Zi :=
Ti;
isOverLimit := Zr*Zr + Zi*Zi > limit2;
IF isOverLimit THEN EXIT; END;
END;

!
I

;
I

IF isOverLimit THEN
byteacc := Word.Xor(Word.LeftShift(byteacc, 1), 16_00);
ELSE
byteacc := Word.Xor(Word.LeftShift(byteacc, 1), 16_01);
END;

INC(bitnum);

I
I
I

;
IF bitnum = 8 THEN
;
Wr.PutChar(Stdio.stdout, VAL(byteacc, CHAR));
|
byteacc := 0;
!
bitnum := 0;
!
ELSIF x = width - 1
THEN

byteacc := Word.LeftShift(byteacc, 8 - (width MOD 8));


|
Wr.PutChar(Stdio.stdout, VAL(byteacc, CHAR));
;
byteacc := 0;
!
bitnum := 0
I
END;
I
Wr.Flush(Stdio.stdout);
| END;
| END;
!END Mandelbrot.

MySQL
See http://arbitraryscrawl.blogspot.co.uk/2012/06/fractsql.html for an explanation.

http://rosetlacode.Org/wiki/M andel brot_set#MATLAB

48/78

19/11/2015

M andel brat set - Rosetta Code

i-- Table to contain aLL the data points


CREATE TABLE points (
; C_re DOUBLE, i c_im DOUBLE,
! Z_re DOUBLE DEFAULT 0,
I z_im DOUBLE DEFAULT 0,
znew_re DOUBLE DEFAULT 0,
; znewim DOUBLE DEFAULT 0,
| steps INT DEFAULT 0,
; active CHAR DEFAULT 1
j);

[DELIMITER I
Iterate over aLL the points in the table 'points'
[CREATE PROCEDURE itrt (IN n INT)
[BEGIN
! label: LOOP |
UPDATE points
|
SET
[
znew_re=POWER(z_re,2)-POWER(z_im,2)+c_re,
[
znew_im=2*z_re*z_im+c_im,
[
steps=steps+l
I
WHERE active=l;
UPDATE points SET ;
z_re=znew_re,
[
z_im=znew_im,
[
active=IFCPOWERCz_re,2)+POWER(z_im,2)>4,0,l)
[
WHERE active=l;
! SET n = n - 1;
!
IF n > 0 THEN
;
ITERATE label;

END IF;
[
LEAVE label;
[ END LOOP label;
!END|

-- Populate the table 'points'


CREATE PROCEDURE populate (
[ r_min DOUBLE,
[ r_max DOUBLE,
! r_step DOUBLE,
| i_min DOUBLE,
; i_max DOUBLE,
[ i_step DOUBLE)
[BEGIN
[ DELETE FROM points;
! SET @rl = rmin; j SET
@a = 0;

rloop: LOOP
; SET @im = imin;
[
SET @b = 0;
[
iloop:
LOOP
:
INSERT INTO points (c_re, c_im)
j
VALUES (grl, @im);
|
SET @b=@b+L;
[
SET @im=i_min + @b * i_step;
[
IF @im < i max THEN
[
ITERATE iloop;
!
END IF;
LEAVE iloop;
I END LOOP
iloop;
;
SET @a=@a+L;
[ SET @rl=r_min + @a * r_step;
[
IF @rl
<r_max THEN
I
ITERATE rloop;
|
END IF;
;
LEAVE rloop;
[ END LOOP rloop;
[END |

IDELIMITER ;
-- Choose size and resolution of graph
R_min, R_maXj R_stepj I_min, I_max, I_step [CALL
populate! -2.5, 1.5,
0.005, -2,
2,
0.005 );
!-- Calculate 50 iterations ICALL itrt(
50 );
[-- Create the image (/tmp/image.ppm)
[-- Note, MySQL will not over-write an existing file and you may need [-- administrator access
to delete or move it
[SELECT (Sxmax: =COUNT(c_re) INTO @xmax FROM points GROUP BY c_im LIMIT 1;
[SELECT @ymax:=COUNT:c_im) INTO @ymax FROM points GROUP BY c_re LIMIT 1; [SET
group_concat_max_len=ll*@xmax*@ymax;
PB, @xmax, @ymax, 200,
GROUPCONCAT(
CONCAT(
IF( active=l, 0, 55+M0D(steps, 200) ),

SELECT

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

49/78

19/11/2015

M andel brat set - Rosetta Code

IF( active=l, 0, 55+MOD(POWER(steps,3), 200) ), IF( active=l, 0,


+M0D POWER steps, , 200) ) ) ORDER BY c_im ASC, C_re ASC
SEPARATOR ' ' )
INTO OUTFILE Vtmp/image.ppm'
FROM points;

Nim
Translation of: Python import complex
!proc mandelbrot(a): Complex =
! for i in 0 .. <50:
!
result = result * result + a
[iterator steplt(start, step, iterations) = ; for i in 0 .. iterations:
| yield start + float(i) * step
!var rows = ""
jfor y in steplt(1.0, -0.05, 41):
; for x in stepIt(-2.0, 0.0315, 80):
; if abs(mandelbrot((x,y))) < 2:
;
rows.add('*')
I
else:
!
rows.add(' ')
! rows.add(n\n")
[echo rows

OCaml
#load "graphics.cma";;
[let mandelbrot xMin xMax yMin yMax xPixels yPixels maxlter =
! let rec mandelbrotlterator z c n =
! if (Complex.norm z) > 2.0 then false else !
match n
with
!
| 0 -> true
;
| n -> let z' = Complex.add (Complex.mul z z) c in
;
mandelbrotlterator z' c (n-1) in
! Graphics.opengraph
A
|
(" " (string_of_int xPixels)A"x"A(string_of_int yPixels));
!
let dx = xMax -. xMin)
/.
(float_of_int
xPixels)
!
and
dy
- (yMax yMin)
/.
(float_of_int
[ for xi = 0 to xPixels - 1 do ; for yi = 0 to
yPixels - 1 do
;
let c = (Complex.re = xMin +. (dx *. float_of_int xi);
!
Complex.im = yMin +. (dy *. float_of_int yi)} in
!
if (mandelbrotlterator Complex.zero c maxlter) then
!
(Graphics.setcolor Graphics.white;
;
Graphics.plot xi
yi
)
;
else
!
(Graphics.set_color Graphics.black;
!
Graphics.plot xi
yi
)
! done I
done;;

yPixels) in

mandelbrot (-1.5) 0.5 (-1.0) 1.0 500 500 200;;

Octave
This code runs rather slowly and produces coloured Mandelbrot set by accident (output image).
I ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ^

!#/ /usr/bin/octave -qf


global width = 200;
[global height = 200;
jmaxiter = 100;

;
|

:z0 = 0;
Iglobal cmax = 1 + i;
Iglobal cmin = -2 - i;

:
!
!

^function cs = pscale(c)
! global cmax;
\ global cmin;

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

\
i

50/78

19/11/2015

M andel brat set - Rosetta Code

! global width;
! global height;
; persistent px = (real(cmax-cmin))/width;
; persistent py = (imag(cmax-cmin))/height;
; cs = real(cmin) + px*real(c) + i*(imag(cmin) + py*imag(c)); lendfunction
Ims = zeros(widthJ height); jfor x = :width~l ; for y = 0:height-l !
!
c = pscale(x+y*i);
!
for ic = limaxiter
!
zl = z0A2 + c;
; if ( abs(zl) > 2 ) break; endif |
z0
= zl;
! endfor
I
ms(x+l, y+1) = ic/maxiter;
! endfor lendfor

z0 = 0;

;saveimage("mandel.ppm", round(ms .* 255).', "ppm");

Pascal
Translation of: C program mandelbrot;
const
ixmax = 800;
iymax = 800;
cxmin = -2.5;
cxmax =
1.5;
cymin = -2.0;
cymax =
2.0;
maxcolorcomponentvalue = 255;
maxiteration = 200; escaperadius = 2;
type
colortype = record red : byte; green :
byte; blue : byte;
end;

ix, iy
cx, cy
pixelwidth
pixelheight
filename
comment
outfile
color
zx, zy
zx2, zy2
iteration
er2

integer;
real;
real = (cxmax - cxmin) / ixmax;
real = (cymax - cymin) / iymax;
string = 'newl.ppm';
string = '# ';
textfile;
colortype;
real;
real;
integer;
real = escaperadius * escaperadius);

begin

{Si-}
assign outfile, filename); rewrite(outfile);
if ioresult <> 0 then begin
writeln(stderr, 'unable to open output file:
exit;
end;

filename);

writeln(outfile, 'P6'); writeln(outfile, ' comment); writeln(outfile, '


ixmax); writeln(outfile, ' ', iymax); writeln(outfile, '
maxcolorcomponentvalue);
for iy := 1 to iymax do begin
cy := cymin + (iy - l)*pixelheight; if abs(cy) < pixelheight / 2
then cy := 0.0; for ix := 1 to ixmax do begin
cx := cxmin + (ix - l)*pixelwidth; zx := 0.0; zy :=
0.0; zx2 := zx*zx;

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

51/78

19/11/2015

M andel brot set - Rosetta Code


zy2 := zy*zy; iteration := 0;
while (iteration < maxiteration and (zx2 + zy2 < er2) do begin
zy := 2*zx*zy + cy; zx :=
zx2 - zy2 + cx; zx2 :=
zx*zx; zy2 := zy*zy;
iteration := iteration + 1; end;

begin
color.red
= 0;
color.green = 0;
color.blue
= 0;
end
else
begin
color.red
= 255
color.green = 255
color.blue
= 255
if iteration = maxiteration then
end;
write(outfile, ehr(color.red), chr(color.green), chr color.blue)); end; end;
close(outfile);
end.

Perl
translation / optimization of the ruby solution use Math::Complex;
sub mandelbrot { my ($ z, $c) = for (1 .. 20) {
$z = $z * $z + $c; return $_ if
abs $z > 2;

}
[for (my ty = 1; $y >= -1; $y -= 0.05) {
! for (my $x = -2; $x <= 0.5; $x += 0.0315)

{print mandelbrot($x + $y * i) ? ' ' : '#'}


; print "\n"

Perl 6
Variant of a Mandelbrot script from the Perl 6 ecosystem (http://modules.perl6.org/) . Produces a Portable Pixel Map to
STDOUT. Redirect into a file to save it. Converted to a .png file for display here.
jconstant MAX_ITERATIONS = 50;
|my Jwidth = my $height = +((8*ARGS[0] // 30);
|sub cut Range $r, Int $n where $n > 1) {
! $r.min, * + $r.max - $r.min) / ($n - 1) ... $r.max
;>

|my @re = cut(-2 .. 1/2, $height);


fny $im = [ cut( 0 .. 5/4, $width div 2 + 1) X* li ];
constant @color_map = map ~*.comb(/../) .map({ :16($_), <
I00000 0000f C 4000fc 7c00fc bc00fc fC00fc fc00bc fc007c
0Ifc7c00 fcbc00 fcfC00 bcfc00 7cfc00 40fC00 00fC00 00fc40
00bcfc 007cfc 0040fc 7c7cfc 9c7cfc bc7cfc dc7cfc fc7cfc
Jfc7c7c fc9c7c fcbc7c fcdc7c fcfc7c dcfc7c bcfc7c 9cfc7c
[7cfcdc 7cfcfc 7cdcfc 7cbcfc 7c9cfc b4b4fc c4b4fc d8b4fc
Ifcb4d8 fcb4c4 fcb4b4 fcc4b4 fcd8b4 fce8b4 fcfcb4 e8fcb4
Ib4fcc4 b4fcd8 b4fce8 b4fcfc b4e8fc b4d8fc b4c4fc 000070
>700070 700054 700038 70001c 700000 701C00 703800 705400
1C700 007000 00701c 007038 007054 007070 005470 003870
0
543870
603870 703870 703860 703854 703844 703838 704438
I607038 547038 447038 387038 387044 387054 387060 387070
1505070 585070 605070 685070 705070 705068 705060 705058
1706850 707050 687050 607050 587050 507050 507058 507060
>506070 505870 000040 100040 200040 300040 400040 400030
401000402000 403000 404000 304000 204000 104000 004000

http://rosetlacode.org/wiki/M andel brot_set#MATLAB

fc0040
00fc7c
fc7cdc
7cfc7c
e8b4fc
d8fcb4
1C0070
707000
001C70
705438
386070
705050
507068
400020
004010

f C0000
00fcbc
fc7cbc
7cfc9c
fcb4fc
c4fcb4
380070
547000
383870
706038
385470
705850
507070
400010
004020

fc4000
00fCfC
fc7c9c
7cfcbc
fcb4e8
b4fcb4
540070
387000
443870
707038
384470
706050
506870
400000
004030

52/78

19/11/2015
[004040
J402028
;204030
|402c3c
I2c402c
;>;

003040 002040
402020 402820
204038 204040
402c34 402c30
2c4030 2c4034

Mandelbrot set - Rosetta Code


001040
403020
203840
402c2c
2c403c

202040
403820
203040
40302c
2c4040

282040 302040
404020 384020
202840 2c2c40
40342c 403c2c
2c3c40 2c3440

382040
304020
302c40
40402c
2c3040

402040
284020
342c40
3c402c

402038 402030
204020 204028
3c2c40 402c40
34402c 30402c

;sub mandelbrot Complex $c ) {


! my $im2 = $c.im**2;
I return 0 if ($c.re + 1)**2 + $im2 < 1/16;
! my $q = ($c.re - l/4)**2 + $im2;
! return 0 if $q*($q + ($c.re - 1/4)) < $im2/4;
; my $z = 0i;
| for AMAX_ITERATIONS -> $i {
!
return $i + 1 if $z.re**2 + $z.im**2 > 4;
!
$z = $z * $z + $cj

i}
!

return 0;

[my @promises = map ~> $re {

! start { [ mandelbrot($re + $_) for @$im ] }


;}, @re;

jsay "P3";
;say "$width $height";
|say "255";
[for @promises.result {
I say @color_map flat .reverse, .[l..*])[A$width]];

Phix
Ascii
This is included in the distribution (with some extra validation) as demo\mandle.exw

-- Mandlebrot set in ascii art demo.


constant b=" .:,;!/>)|&IH%*#" atom r, i,
c, C, z, Z, t, k for y=30 to 0 by -1 do C
= y*0.1~1.5 puts(1,'\n') for x=0 to 74
do c = x*0.04-2 z = 0 Z = 0 r = c i = C
k=0
while k<112 do t =
z*z-Z*Z+r Z =
2*z*Z+i z = t
if z*z+Z*Z>10 then exit end if k += 1
end while
puts(l,b[remainder(k,16)+l]) end
for end for

Graphical
This is included in the distribution as demo\arwendemo\mandel.exw
[include arwen.ew
[include . .\arwen\dib256.ew

J
[

Iconstant HelpText = "Left-click drag with the mouse to move the image.\n"&
I
" (the image is currently only redrawn on mouseup).\n"&
;
"Right-click-drag with the mouse to select a region to zoom in to.\n"&
;
"Use the mousewheel to zoom in and out (nb: can be slow).\n"&
[
"Press F2 to select iterations, higher==more detail but slower.\n"&
!
"Resize the window as you please, but note that going fullscreen, \n"&
!
"especially at high iteration, may mean a quite long draw time.\n"&
!
"Press Escape to close the window."

[procedure Help()
[ void = messageBox("Mandelbrot Set",HelpText,MB_OK)
lend Drocedure

[
[
!

http://rosetlacode.org/wi ki/M andel brot_set#M ATLAB

;
;
[
!
!
I

53/78

19/11/2015

M andel brat set - Rosetta Code

integer cWidth = 520 -- client area width integer


cHeight 480 -- client area height
constant Main = create(Window, "Mandelbrot Set"; 0, 0, 50, 50, cWidth+16, mainHwnd
= getHwnd(Main), mainDC = getPrivateDC(Main),
miter - create(Menu, 0, 0, 0,0,0,0,0), iterHwnd =
getHwnd(mlter),
mlter50 = create(MenuItem,"50 (fast, low detail)", 0, miter, mlterl00 =
create(MenuItem,"100 (default)",
0, miter,
mlter500 = create(MenuItem,"500",
0, miter,
mlterl000 = create(MenuItem,"1000 (slow, high detail)",0, miter, m50tol000
= {mlter50,mlterl00,mlter500,mlterl000}, i50tol000 = {
50,
100,
500,
1000}

cHeight+38, 0),

0, 0, 0, 0, 0),
0, 0, 0, 0, 0),
0, 0, 0, 0, 0),
0, 0, 0, 0, 0),

integer mainDib = 0
constant whitePen = c_func(xCreatePen, {0,l,BrightWhite}) constant NULL_BRUSH =
5,
NullBrushID = c_func(xGetStockObject,{NULL_BRUSH})
Satom t0 integer iter
Satom x0, y0
-- top-left coords to draw
jatom scale

-- controls width/zoom

[procedure init()
!

X0 =

-2

1
y0 =
-1.25
| scale = 2.5/cHeight | iter
= 100
;
void c_func(xSelectObject,{mainDC,whitePen})
!
void = c_func(xSelectObject,{mainDC,NullBrushID})
Send procedure
!init()
^function in_set(atom x, atom y)
[atom u,t
S if x>-0.75 then S
u = x-0.25
S
t = u2u+y*y
|
return ((2*t+u)*(2*t+u)>t)
;
else
2
return ((x+l)*(x+l)+y*y)>0.0625 2 end if
Send function
function pixel_colour(atom x0, atom y0, integer iter) [integer count = 1 jatom x 0, y = 0

S while (count<=iter) and (x*x+y*y<4) do !


count
+= 1
!
{x,y}
= {x*x-y*y+x0,2*x*y+y0}

end while
; if count<=iter then return count end if ; return 0 Send function
Sprocedure mandel(atom x0, atom y0, atom scale)
Satom x,y integer c ; t0 = time()
:
y = y0

!
S
S

;
;
S
!
S
S

for

yi=l tocHeight
do
x = x0
for xi=l tocWidth do
c = 0 default to black
if in_set(x,y)
then
c = pixel_colour(x,y,iter)
end if
setDibPixel(mainDib,
xi, yi, c)
x += scale

end for
y += scale

;
end for
Send procedure

Sinteger firsttime = 1 [integer drawBox = 0 [integer drawTime = 0


[procedure newDib()
Ssequence pal

2
[
!

if mainDib!=0 then
{} =
deleteDib(mainDib)
end if
S mainDib = createDib(cWidth, cHeight)
S
pal = repeat({0,0,0},256)
http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

54/78

19/11/2015
; for i=2 to 256 do
1
pal[i] [1]
:

pal[i][2]

M andel brat set - Rosetta Code


= i*5
= 0

!
pal[i][3]
= i*10
! end for
| setDibPalette(mainDib, 1, pal)
; mandel(x0,y0,scale)
2
drawTime = 2
Send procedure
^procedure reDraw()
; setText(Main,"Please Wait...")
2 mandel(x0,y0,scale)
2 drawTime - 2 S
repaintWindow(Main,False)
Send procedure
jprocedure zoom(integer z)

2 while z do 2
if z>0 then
S
scale /=
S
z -= 1
!
else
;
scale *=
;
z += 1
2
end if
S end while S
reDraw()

1.1

1.1

Send procedure

Jinteger dx=0,dy=0
Jinteger mx=0,my=0

-- mouse down coords


-- mouse move/up coords

Sfunction mainHandler(integer id, integer msg, atom wParam, object lParam)


Sinteger
x, y
-- scratch vars
;atom scalel0

2 if msg=WM_SIZE then -- (also activate/firsttime)


1
{{}j{)jx>y} = getClientRect(Main)
S
if firsttime or
cWidth!=x or cHeight!=y then
|
scale *= cWidth/x
;
{cWidth, cHeight} =
{x,y}
2
newDib()
2
firsttime = 0
S
end if
1
elsif msg=WM_PAINT then
S
copyDib(mainDC, 0, 0, mainDib)

if drawBox then
;
void = c_func(xRectangle, {mainDC, dx, dy, mx, my})
;
end if
S
if drawTime then
S
if drawTime=2 then
S
setText(Main,sprintf("Mandelbrot
Set [generated in %gs]",time()-t0))
else

;
setText(Main,"Mandelbrot Set")
2
end if
S
drawTime -= 1
S
end if
j elsif msg=WM_CHAR then ;
if
wParam=VK_ESCAPE then
2
closeWindow(Main)
2
elsif wParam=,+ then zoom(+l)
S
elsif wParams'-' then zoom(-l)
S
end if
!
elsif
msg=WM_LBUTTONDOWN
;
or
msg=WM_RBUTTONDOWN then
;
{dx,dy} = lParam
S elsif msg=WM_MOUSEMOVE then !
if
and_bits(wParam,MK_LBUTTON)
then
S
{mx,my} = lParam
j
-- minus dx,dy (see
WM_LBUTTONUP)

-- DEV maybe a timer to redraw, but probably too slow...


2
-- (this is where we need a background worker thread,
2
-ideally one we can direct to abandon what it is
S
-currently doing and start work on new x,y instead)
I
elsif and_bits(wParam,MK_RBUTTON) then
1
{mx,my} lParam
2
drawBox = 1
2
repaintWindow(Main,False)
2
end if
1
elsif
msg=WM_MOU5EWHEEL then
S
wParam = floor(wParam/#10000)
S
if wParam>=#8000 then -- sign bit
set

wParam-=#10000
;
end if
2
wParam floor(wParam/120) --(gives +/-1, usually)
!
zoom(wParam)
!
elsif
msg=WM_LBUTTONUP then

{mx,my} = lParam
2
drawBox = 0
;

x0 += (dx-mx)*scale

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

55/78

19/11/2015

Mandelbrot set - Rosetta Code

y0 += (dy-my)*scale

reDraw()

| elsif msg=WM_RBUTTONUP then ;


{mx,my} = lParam
|
drawBox = 0
!
if mx!=dx and my!=dy
then
!
x0 += min(mxJdx)*scale
!
y0 += min(my,dy)*scale
j
scale *= (abs(mx-dx))/cHeight

reDraw()

J
end if
! elsif msg=WM_KEYDOWN then !
if wParam=VK_Fl then

Help()

!
|
I
!
!

elsif wParam=VK_F2 then


{x,y} = getWindowRect(Main)
void = c_func(xTrackPopupMenu,
{iterHwnd,TPM_LEFTALIGN,x+20,y+40,0,mainHwnd,NULL})
elsif find(wPa ram,{VK_UP,VK_DOWN,VK_LE FT,VK_RIGHT}) then
drawBox = 0
scalel0 = scale*10
if wParam=VK_UP then
y0 += scalel0
elsif wParam=VK_D0WN then
y0 -= scalel0
elsif wPanam=VK_LEFT then
x0 += scalel0
elsif wParam=VK_RIGHT then
x0 -= scalelO
end if

;
|
!
!
!
;
;
J

reDrawQ

!
end if
| elsif msg=WM_COMMAND then ; id
= find(id,m50tol000)
;
if idl=0
then
!
iter = i50tol000[id]
!
reDraw()
!
end if
i end if ; return 0
;end function
[setHandler ({Main,mlter50,mlterl00,mlter500,mlterl000}, routine_id("mainHandler"))
IWinMain (Main, SW_NORMAL)
!void = deleteDib(0)

PHP
Library: GD Graphics Library
Works with: PHP version 5.3.5
;$min_x=-2;
!$max_x=l;
!$min_y=-l;
!$max_y=i;
|$dim_x=400;
;$dim_y=300;
!$im = @imagecreate($dim_x, $dim_y}i
! or die("Cannot Initialize new GD image stream");
'header("Content-Type: image/png");
j$black_color = imagecolorallocate($im, 0, 0, 0);
;$white_color = imagecolorallocate $im, 255, 255, 255);
!for($y=0;$y<=$dim_y;$y++) {
! for($x=0;$x<=$dim_x;$x++) {
! $cl=$min_x+($max_x-$min_x)/$dim_x*$x;
;
$c2=$min_y+($max_y-$min_y)/$dim_y*$y;
I $zi=0;

$z2=0;

j for($i=0;$i<100;$i++) {
|
$newl=$zl*$zl-$z2*$z2+$cl;
;
$new2=2*$zl*$z2+$c2;
|
$zl=$newl;
!
$z2=$new2;
j
if($zl*$zl+$z2*$z2>=4) {
!
break;
|

>

>

:
!

if($i<100) {
imagesetpixel ($im, $x, $y, $white_color);

>

;}
!>

http://rosettacode.org/wiki/Mandelbrot_seWMATLAB

56/78

19/11/2015

M andel brat set - Rosetta Code

imagepng($im); imagedestroyi$im

);

PicoLisp
(scl 6)
(let Ppm (make (do 300 (link (need 400))))
(for (Y . Row) Ppm (for
(X . @) Row
(let (ZX 0 ZY 0 CX (*/ (~ X 250) 1.0 150) CY (*/ (~ Y 150) 1.0 150) C 570) (while (and (> 4.0 (+ (*/
ZX ZX 1.0) (*/ ZY ZY 1.0))) (gt0 C))
(let Tmp (~ (*/ ZX ZX 1.0) (*/ ZY ZY 1.0) (~ CX))
(setq
ZY (+ (*/ 2 ZX ZY 1.0) CY)
ZX Tmp ) )
(dec 'C) )
(set (nth Ppm Y X) (list 8 C C)) ) ) )
(out "img.ppm"
(prinl "P6")
(prinl 400 " " 300)
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) )

PostScript
j%!PS-Adobe-2.0
MBoundingBox: 0 0 300 200
;%%EndComments
[/origstate save def
I/ld {load def} bind def
!/m /moveto Id /g /setgray Id
I/dot { currentpoint 1 0 360 arc fill } bind def
%%EndProlog
;% param
!/maxiter 200 def
!% complex manipulation
I/complex { 2 array astore } def
I/real { 0 get } def
/imag { 1 get } def

;/cmul { /a exch def /b exch def


!
a real b real mul
!
a imag bimag mul sub
!
a real bimag mul
!

imag b real

mul add

;
2 array astore
;} def
;/cadd { aload pop 3 -1 roll aload pop !
3 -1 roll
add
!
3 1 roll add exch 2 array astore
!} def
;/cconj { aload pop neg 2 array astore } def ;/cabs2 { dup
cconj cmul 0 get} def % mandel
!200 100 translate 1-200 1 100 { /x exch def \
-100 1
100 { /y exch def
;
/z0 0.0 0.0 complex def
;
0 1 maxiter { /iter exch def
!
x 100 div y 100 div complex
!
z0 z0 cmul
!
cadd dup /z0 exch
def
!
cabs2 4 gt {exit}
if
!
} for
;
iter maxiter div g
! x y m dot ! } for !} for
j%
jshowpage
Jorigstate restore !%%EOF

Prolog
SWI-Prolog has a graphic interface XPCE :
use moduleClibrary(pce)).

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

http://rosettacode.Org/wiki/M andel brot_set#M ATLAB

56/78

57/78

19/11/2015
|mandelbrot
; new D, window('Mandelbrot Set1)),
! send D, size, size(700, 650)),
! new(lmg, image;@nil, width := 700, height := 650, kind := pixmap)),
|

fora11(between(0,699, I),

|
!
I
!
;
;
;
;
!

( forall between(0,649, 1),


( get_RGB I, :, R, G, B),
R1
is (R * 256) mod
65536,
G1
is (G * 256) mod
65536,
B1
is (B * 256) mod
65536,
send(Img, pixel(I, 3, colour (Sdefault, Rl, Gl, Bl))))))),
new(Bmp, bitmap Img)),
send D, display, Bmp,
point(0,0)),
send D, open).

jgetRGB X, Y, R, G, B)
;
CX is (X
- 350) / 150,

CY is (Y
- 325) / 150,
!
Iter = 570,
I compute_RGB(CX, CY, 0, 0, Iter, It),
! IterF is It \/ It 15,
|
R is IterF 16,
; Iterl is IterF - R 16,
;
G is Iterl 8,
:
B is Iterl - G 8.
Icompute_RGB(CX, CY, ZX, ZY, Iter, IterF)
| ZX * ZX + ZY * ZY < 4,
;
Iter > 0,

!
;
Tmp is ZX
* ZX - ZY * ZY + CX,
I
ZY1 is 2
* ZX * ZY + CY,
!
Iterl is Iter - 1,
! compute_RGB CX, CY, Tmp, ZY1, Iterl, IterF).
compute RGB(_CX, _CY, ZX, _ZY, Iter, Iter).

Example:

M andel brat set - Rosetta Code

19/11/2015

M andel brat set - Rosetta Code

PureBasic
PureBasic forum: discussion (http://www.purebasic.fr/german/viewtopic.php?f=4&t=22107)
EnableExplicit

;#Windowl
=
!#Imagel
=
!#ImgGadget =

0
0
0

;
;
!

I#max_iteration =
64
jtfwidth
= 800
j#height
= 600
[Define, d x0 ,y0 ,xtemp ,cr,
pefine.i i, n, x, y ,Event ,color
Oim Color.1 (255)
;For n = 0 To 63
;
Color( 0
;
Color( 64
!
Color( 128
\
Color( 192
Next

+n
+n
+n
+n

)
)
)
)

=RGB(
=RGB(
=RGB(
=RGB(

ci

n*4+128, 4
* n, 0 )
64, 255, 4 * n )
64, 255 - 4 * n ,
255 )
64, 0, 255 - 4 * n )

!
|
;
J
!
j
;
j
;
\
!

[If OpenWindow(#Windowl,
0, 0,#width, #height, "'Mandelbrot set' PureBasic Example", #PB_Window_SystemMenu )
I If CreateImageC#Imagel, #width, #height)
!
ImageGadgetC#ImgGadget, 0, 0, #width, #height, ImagelD #Imagel))
!
For y.i = 1 To #height -1

StartDrawing ImageOutput #Imagel))


;
For x.i = 1 To #width -1
;
x0 = 0

[
|
!
!
!
;
;

y0 = 0;

:
I
;
;

cr = (x
/ #width *2.5
-2
ci = (y
/ #height)*2.5 -1.25
i=0
While (x0*x0 + y0*y0
<=4.0) And i < #max_iteration

!
!
|
j

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

59/78

19/11/2015

M andel brat set - Rosetta Code

i +1

xtemp = x0*x0 - y0*y0 + cr y0 =


*x0*y0 + ci
x0 = xtemp
blend
If i >= #max_iteration
Plot(Xj ya 0 )
Else
Plot(x, y, Color(i & 255))
Endlf
Next
StopDrawingQ
SetGadgetState #lmgGadget, ImagelD #Imagel i
Repeat
Event = WindowEvent )
If Event = #PB_Event_CloseWindow
End
Endlf
Until Event = 0 Next Endlf Repeat
Event = WaitWindowEventQ Until Event
= #PB_Event_CloseWindow Endlf

Example:

Python
Translation of the ruby solution ;# Python 3.0+ and 2.5+
Jtry:
! from functools import reduce !except:
pass

http://rosetlacode.org/wiki/M andel brot_set#MATLAB

60/78

19/11/2015

M andel brat set - Rosetta Code

;def mandelbrot(a):
! return reduce lambda z, _: z * z + a, range 50 , 0)
Idef step start, step, iterations):
! return (start + (i * step) for i in range(iterations))
;rows = (("*" if abs mandelbrot complex x, y))) < 2 else " " ; for x in
step(-2.0, .0315, 80))
!
for y in step(l, -.05, 41))
Iprint("\n".join("".join(row) for row in rows))

A more "Pythonic" version of the code: import math


def mandelbrot(z , c , n=40): if abs(z)
> 1000:
return float("nan") elif n
> 0:
return mandelbrot(z ** 2 + c, c, n - 1) else:
return z ** 2 + c
print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0, x + lj * y).real] else " for x in [a * 0.02 for a in range(80, 30)]]) for y in [a * 0.05 for a in range(-20, 20)]])

Finally, we can also use Matplotlib to visualize the Mandelbrot set with Python:
Library: matplotlib
Library: numpy
;from pylab import *
Jfrom numpy import NaN
Idef m(a):
|
z=0
;
for n in range(l, 100):
i
z _ z**2 + a
;
if abs(z) > 2:
!
return n
I
return NaN
jx = arange(-2, .5, .002)

JY = arange(-l, 1, .002)
:z = zeros((len(Y), len(X)))
If or iy, y in enumerate (Y):
I
print (iy, "of", len(Y))
;
for ix, x in enumerate X):
l
Z[iy,ix] = m(x + lj * y)
limshow(Z, cmap = pit.cm.prism, interpolation = 'none', extent = (X.min(), X.max , Y.min(), Y.max())) Ixlabel(" Re(c)")
Iy label ("Im(c)")
jsavef ig("mandelbrot_python. svg")
;show()

iterate.until.escape <- function(z, c, trans, cond, max=50, response=dwell) { #we iterate all active
points in the same array operation,
#and keeping track of which points are still iterating.
active <- seq_along(z)
dwell <- z
dwell[] <- 0
for (i in l:max) {
z[active] <- trans(z[active], c[active]); survived <cond(z[active]) dwell[active[survived]] <- i active <active[survived] if (length(active) == 0) break
>

eval(substitute(response))

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

61/78

19/11/2015

M andel brat set - Rosetta Code

re = seq(-2, 1, len=500)
;im = seq(-1.5, 1.5, len=500)
|c <- outer(re, im, functlon(x,y) complex(rcal=x, imaginary=y))
|x <- Iterate.until.escape(array(0, dim(c)), c,
!
function(z,c)zA2+c, function(z)abs(z) <= 2,
'
max=100)
jimage(x)

Racket
#lang racket
[(require racket/draw)
[(define (iterations a z i)
! (define z' (+ (* z z) a))
I (if (or (= i 255) (> (magnitude z') 2))
;
i
;
(iterations
a z* (addl

i))))

[(define (iter->color i)
[ (if (= i 255)
!
(make-object
color% "black")

(make-object color% (* 5 (modulo i 15)) (* 32 (modulo i 7)) (* 8 (modulo i 31)))))


[(define (mandelbrot width height)
[ (define target (make-bitmap width height))
! (define dc (new bitmap-dc% [bitmap target]))
| (for* ([x width] [y height])
;
(define real-x (- (* 3.0 (/ x width)) 2,25))
;
(define real-y (- (* 2.5 (/ y height)) 1.25))
[ (send dc set-pen (iter->color (iterations (make-rectangular real-x real-y) 0 0)) 1 solid) [ (send dc draw-point x y))
! (send target save-file "mandelbrot.png" png))
(mandelbrot 300 200)

REXX
version 1
Translation of: AWK
This REXX version doesn't depend on the ASCII sequence of glyphs; an internal character string was used that mimics a part of the ASCII glyph
sequence.
/*REXX program generates and displays a Mandelbrot set as a character image.*/ = >=<;:9876543210/.
'&%$#"!'
/*characters used in display.*/
[Xsize = 59; minRE = -2; maxRE = +1;
stepx = (maxRE-minRE) / Xsize
[Ysize = 21; minIM = -1; maxIM = +1;
stepY = (maxIM-minIM) / Ysize

,+*)('

do y=0 for ysize;

im=minIM + stepY*y

$=

do x=0 for Xsize; re=minRE + stepX*x; zr=re; zi=im if a+b>4 then


,>>>>>>=====<<<<<<<<<<<<<<<
::96032:;;;;<<==========
;:: :873*079:: ;;;;<=======
!>===<<;
do n=0 for 30;
a=zr**2;
leave
b=zi**2; (.9: :::;;<======
;===<<<;
:9974
zr=a-b+re
zi=zr*zi*2 + im; end
;>==<;;;
5789999: ;;<====
98888764 996.
/*n*/
[>>==<<<<<;;;;::
&2 99975245335:;=== *79:;== %78: ;;=
[=<;
+9;;< *9:::
$=$ 11 substr n+1., 1) end /*x*/
/*append number (as a char) to $ string*/
!>=;;;: 599999999886 !>;;;;;: :
:972456-567763 9875&
.3
/*display a line of character output.*/ /*stick a fork in it>
say
$
/*y*/
we're all done. */
end

output using the internal defaults:

http://rosetlacode.org/wiki/M andel brot_set#MATLAB

62/78

19/11/2015

M andel brot set - Rosetta Code

8:;;; 889:;;;
5;;;;;;::997564'
&89:;;;<< 8:;;; *9;;;
: 988897735/
+9;;< %78: ;;=
:>: =988897735/
*79:;== 45335:;===
!>;;;;;;: =997564'
5789999: ;;< -----------=98758
.3
( . 9 : : : :;;<======
: =972456-567763
:>=;;;:599999999886 ! = < < < ; = 9 9 9 7 5 2 ==<;;;;::: =996. 82 >==<;; ;;;;: 98888764 ===<;;;;;;;: =9974

version 2
This REXX version uses glyphs that are "darker" (with a white background) around the output's peripheral.
\/*REXX program generates and displays a Mandelbrot set as a character image.*/ j@ = 'BBl@9876543210=.-,+*)(&%$#"!' /*characters used in display.*/
;Xsize = 59; minRE = -2; maxRE = +1;
stepx = (maxRE-minRE) / Xsize

im=minIM + stepY*y re=minRE

do y=0 for ysize;


$=

do x=0 for Xsize;

do n=0 for 30;


zi=zr*zi*2 + im; end
/*n*/
$=$ || substr n+1, 1) end

+ stepX*x;

zr=re; zi=im if a+b>4 then

a=zr**2;

b=zi**2;
zr=a-b+re

leave

/*append number (as a char) to $ string*/

/*x*/

/*display a line of character output.*/ /*stick a fork in it,


we're all done. */
stepY = maxIM-minIM / Ysize

say
$
/*y*/
end
JYsize = 21; minIM = -1; maxIM = +1;

output using the internal defaults:

version 3
This REXX version produces a larger output (it uses the full width of the terminal screen (less one), and the height is one-half of the width.

'BB!

/*REXX program generates and displays a Mandelbrot set as a character image.*/ $ =


@9876543210=.-,+*)(&%$#"!'
'parse arg Xsize Ysize .
/*get optional args from C.L.*/
if Xsize==' then Xsize=linesize()-1
/*X: the linesize (less 1).*/
|if Ysize==J1 then Ysize=Xsize%2 + (Xsize//2==1) /*Y: XLinesize (make it even)*/ fninRE = -2; maxRE = +1; stepX =
(maxRE-minRE) / Xsize
jninIM = -1;
maxIM = +1;
stepY = (maxIM-minIM) / Ysize
do y=0 for ysize;

^characters used in display.*/

im=minIM + stepY*y

$=

do x=0 for Xsize;

re=minRE + stepX*x;

do n=0 for 30; a=zr**2;


zi=zr*zi*2 + im;
end /*n*/

b=zi**2;
zr=a-b+re

http://rosetlacode.Org/wiki/M andel brot_set#M ATLAB

zr=re;

zi=im

if a+b>4 then leave

63/78

19/11/2015

M andel brat set - Rosetta Code

$=$ || substr(@, n+1, 1)


end
/*x*/
say $
end

/*append number (as a char) to $ string*/


/*display a Line of character output.*/
/*stick a fork in it> we're all done. */

/*y*/

output using the internal defaults:


This REXX program makes use of linesize REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal
@@@@985164(9@
iiiiii@@@@98763=5799@
::
fi@@@@98763. 2789@@@!iiii ...@@@@985
@@@999874
*=79@@@@@.....
2.
||@@999998873
17899@@@@@
1448@@@
@@98888888764
#4678899999@@:
@J343,665
322= @@@@@9986
@@@@@@@999863 +

+ 32

I!
>@@@@@@@@@@9998763
@@@@@@@@@@999986.2 $
@689999@@@99999887
ill@@9717888877888888763. i
@@@996)566761467777762
343
@@@@@@98
,@@@@99763 & 42&..36665111

+689@@i
05789@
2558@f!

.68#

864*
:::::!!!i@@@@@@988753.
::::::
@@@@@9877650
|@9999887%413+
|@@@@@89999888763 % (
@@99872676676422
@@99872676676422
i;i@@@@@89999888763 % (
1@9999887%413+
......@@@@@9877650
11
|||@@@@@@988753.
$ 343
::::: I:|:@@@@@@98864*
@@@@99763 & 42&..366651*

259@
!
#9@
:

289@f|

!::@@@996) 566761467777762
@@9717888877888888763. I689999@@@99999887
199986.2 $
!I I i :@@@p@@@@@9998763
|@@@@@@@999863 +
:::::::::
@@@@@9986 + 32
''.'.'.'.'.'.'.'.'.'.@@@@9343,665
322=

I ..

=215357888709@
, 56554)79^1 2",59@fc: $
379@
@.

@@9888888876
4
======@@9999
98873
@@@999874
@@@@985 2.
@@@@98763
1@@@@98763=579!

&69@@
389@@!
5789@
@
5789@
@
389@@
&69@@
289#

#9@|
259#j .
68@
2558#;
05789#
+689@#i $
379@
@

2* ",59@
,56554)79#;
=215357888709#:;;
#4678899999@@i
17899@@@@@
*=79@@@@@ SJJ
1448@@@@:::
2789@@@i!i;;

(console).
The LEVESIZE.REX REXX program is included here ----------- LINESIZE.REX.

Ruby
Text only, prints an 80-char by 41-line depiction. Found here (http://www.xcombinator.eom/2008/02/22/ruby-inject-and-the-mandelbrot- set/).
[require 'complex'
Idef mandelbrot(a)
! Array.new(50).inject(9) { |z,c| z*z + a } lend
;(l.0).step(-i,-0.05) do |y|
!
(-2.0).step(0.5,0.0315) do |x|
! print mandelbrot(Complex(x,y)).abs < 2 >
! end puts
end

:''

Translation of: Tel


Uses the text progress bar from Median filter#Ruby

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

64/78

19/11/2015

M andel brat set - Rosetta Code

class RGBColour
def self.
lel_colour i
self.new( 16*(i % 15), 32*(i % 7), 8*(i % 31) )
end
end
class Pixmap
def self.mandelbrot(width, height) mandel =
Pixmap.new(width,height) pb = ProgressBar.new(width) if
$DEBUG width.times do |x| height.times do |y|
x_ish = Float(x - width*ll/15) / (width/3) y_ish = Float(y - height/2)
/ (height*3/10)
mandel[x,y] = RGBColour.mandel_colour(mandel_iters(x_ish, y_ish)) end
pb.update(x) if $DEBUG end
pb.close if $DEBUG mandel
end
def self.mandel_iters(cx,cy)
x = y = 0.0 count = 0
while Math.hypot(x,y) < 2 and count < 255 x, y = (x**2 - y**2 + cx),
(2*x*y + cy) count += 1 end count end end
Pixmap.mandelbrot(300,300).save('mandel.ppm')

Scala
Works with: Scala version 2.8
Uses RgbBitmap from Basic Bitmap Storage task and Complex number class from this programming task.
[import org.rosettacode.ArithmeticComplex._
[import java.awt.Color
lobject Mandelbrot

;{
; def generate width:Int =600, height:Int =400)={
;
val
bm=new RgbBitmap(width, height)
!
!
!
;
;

val
val
val
val
val

maxlter=1000
xMin = -2.0
xMax = 1.0
yMin = -1.0
yMax = 1.0

[
!

val
val

cx=;(xMax-xMin)/width
cy=(yMax-yMin)/height

;
[
!

for(y <- 0 until bm.height; x <- 0 until bm.width){


val c=Complex(xMin+x*cx, yMin+y*cy)
val iter=itMandel(c, maxlter,
4)
bm.setPixel(x, y, getColor(iter, maxlter))

>

bm

i>
[ def itMandel(c:Complex, imax:Int, bailout:Int):Int={
[
var z=Complex()
!
for(i <0 until imax){
|
z=z*z+c;

if z.abs > bailout) return i

>

imax;

;>

! def getColor(iter:Int, max:Int):Color={


;
if (iter==max) return Color.BLACK
[ var c=3*math.log(iter)/math.log(max-1.0)
I
if(c<l) new Color((255*c).tolnt, 0, 0)
!
else if(c<2) new Color(255, (255*(c-l)).tolnt, 0)
!
else new
Color(255,255, (255*(c-2)).tolnt)

|}
:>

Read-eval-print loop [import scala.swing._


[import javax.swing.Imagelcon
!val imgMandel=Mandelbrot.generate()
Ival mainframe=new MainFrame(){title="Test"; visible=true ! contents=new
Label(){icon=new Imagelcon imgMandel.image))

i>

Scheme
This implementation writes an image of the Mandelbrot set to a plain pgm file. The set itself is drawn in white, while the exterior is drawn in black.
http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

65/78

19/11/2015

M andel brat set - Rosetta Code

(define x-centre -0.5)


(define y-centre 0.0)
(define width 4.0)
(define i-max 800)
(define j-max 600)
(define n 100)
(define r-max 2.0)
(define file "out.pgm")
(define colour-max 255)
(define pixel-size (/ width i-max))
(define x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1)))) (define y-offset (+ y-centre (* 0.5 pixel-size (+ j-max 1))))
(define (inside? z)
(define (*inside? z-0 z n)
(and (< (magnitude z) r-max)
(or (= n 0)
(inside? z-0 (+ (* z z) z-0) (- n 1)))))
(inside? z 0 n))
(define (boolean->integer b)
(if b colour-max 0))
(define (pixel i j)
(boolean->integer (inside?
(make-rectangular (+ x-offset (* pixel-size i))
(- y-offset (* pixel-size j))))))
(define (plot)
(with-output-to-file file (lambda ()
(begin (display "P2") (newline)
(display i-max) (newline)
(display j-max) (newline)
(display colour-max) (newline)
(do ((j l (+ j l))) ((> j j-max))
(do ((i 1 (+ i 1))) ((> i i-max))
(begin (display (pixel i j)) (newline))))))))
(plot)

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

66/78

19/11/2015

M andel brat set - Rosetta Code

Scratch

Sass/SCSS
!$canvasWidth: 200;
!$canvasHeight: 200;
^iterations: 20;
!$xCorner: -2;
|$yCorner: -1.5;
;$zoom: 3;
;$data: ()!global;
!@mixin plot ($xJ$yJ$count){
! $index: ($y * $canvasWidth +
$x) * 4;
| $r: $count * -12 + 255;
| $g: $count * -12 + 255;
; $b: $count * -12 + 255;
; $data: append $data, $x + px $y + px 0 rgb($rJ$gJ$b)J comma)!global;
:>
@for $x from 1 to $canvasWidth

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

|
!
!
I
;
;
J
I
!
!
;
;
!
;

67/78

19/11/2015
; @for $y from 1 to $canvasHeight {
$count: 0;
{size: 0;
$cx: {xCorner + (($x * {zoom / JcanvasWidth);
{cy: SyCorner + (($y * $zoom) / {canvasHeight ;

M andel brat set - Rosetta Code


;

$zx: 0;
$zy: 0;
gwhile {count < {iterations and {size <= 4 {
{count: {count + 1;
{temp: ({zx * {zx) - ({zy * {zy);
{zy: (2 * {zx * {zy) + {cy;
{zx: {temp + {cx;
{size: ({zx * {zx) + ({zy * {zy);
>

^include plot {x, $y, {count);


>

}
set {

height: lpx; width:


lpx; position:
absolute; top: 50%;
left: 50%;
transform: translate({canvaswidth*0.5px, $canvaswidth*0.5px); boxshadow: {data;

Seed7
;$ include "seed7_05.s7i;
[ include "float.s7i";
! include "complex.s7i;
! include "draw.s7i";
! include "keybd.s7i";
[# Display the Mandelbrot set, that are points z[0] in the complex plane |# for which the
sequence z[n+l] : = z[n] ** 2 + z[0] (n >= 0) is bounded.
I# Since this program is computing intensive it should be compiled with I# hi comp -02
mandelbr
;const integer: pix is 200;
[const integer: max_iter is 256;
Ivar array color: colorTable is max_iter times black;
Iconst func integer: iterate (in complex: z0) is func ; result

; var integer: iter is 1;


! local
! var complex: z is complex.value;
! begin
I z := z0;

while sqrAbs(z) < 4.0 and # not diverged [


!
z
*:= z;
!
z +:= z0;

iter < max_iter do # not converged

!
incr(iter);
! end while;
; end func;

[const proc: displayMandelbrotSet (in complex: center, in float: zoom) is func [


!
var integer: x is0;
!
var integer: y is0;
; var complex: z0 is complex.value;
;
begin
[ for x range -pix to pix do [
for
y range -pix to pix do
!
z0 := center + complex(flt(x) * zoom, flt(y) * zoom);
I
point(x + pix, y + pix,
colorTable[iterate(z0)]);

local

;
end for;
; end for;

[ end func;
Iconst proc: main is func I local

; const integer: numpix is 2 * pix + 1;


; var integer: col is 0;
[
begin
I
screen(num_pix, num_pix);
I
clear(curr_win, black);
I KEYBOARD := GRAPHKEYBOARD;
; for col range 1 to pred(max_iter) do

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

68/78

19/11/2015

M andel brat set - Rosetta Code

colorTable[col] := color(65535 - (col * 5003) mod 65535,


(col * 257) mod 65535, (col
* 2609) mod 65535);
end for;
displayMandelbrotSet(complex(-0.75, 0.0), 1.3 / flt(pix));
DRAW_FLUSH; readln(KEYBOARD); end func;

Original source: [2] (http://seed7.sourceforge.net/algorith/graphic.htm#mandelbr)

Sidef rFunc mandelbrot(z) {


;

var

j
I

c = z;

}*

return false;

z =
(z*z + c);
z.abs > 2 && return true;

20;

1 A.. (-1, 0.05) -> each { |y|


-2 ,.A (0.5, 0.0315) -> each { |x|
print(mandelbrot(y.i + x) ? ' ' : '#');

}
print "\n";

Tel
Library: Tk
This code makes extensive use of Tk's built-in photo image system, which provides a 32-bit RGBA plotting surface that can be then quickly
drawn in any number of places in the application. It uses a computational color scheme that was easy to code...
package require Tk

Iproc mandellters {cx cy) {


! set x [set y 0.0]
! for {set count 0} (hypot($xJ$y) < 2 && $count < 255} {incr count} {
|
set xl [expr $x*$x - $y*$y + $cx>]
;
set yl [expr {2*$x*$y + $cy>]
!
set x $xl; set y $yl
;>

! return $count
;>

;proc mandelColor {iter} {


;
set r [expr {16*($iter % 15)}]
|
set g [expr {32*($iter % 7)}]
I set b [expr {8*($iter % 31)}]
! format "#%02x%02x%02x" $r $g $b
;}
image create photo mandel -width 300 -height 300
;# BuiLd picture in stripsj updating as we go so we have "progress" monitoring \# Also set the
cursor to tell the user to wait while we work.
Ipack [label .mandel -image mandel -cursor watch] lupdate
Jfor {set x 0} {$x < 300} {incr x} {
; for {set y 0} {$y < 300} {incr y} {
;
set i [mandellters [expr {($x-220)/100.}] [expr {($y-150)/90.}]]
!
mandel put [mandelColor $i] -to $x $y
:}
! update }
mandel configure -cursor {}

TeX
Library: pst-ffactal
The pst-fractal package includes a Mandelbrot set drawn by emitting PostScript code (using PSTricks), so the actual work done in the printer
or PostScript interpreter.
Plain TPY

http://rosettacode.org/wi ki/M andel brot_set#M ATLAB

68/78

19/11/2015

M andel brat set - Rosetta Code

\input pst-fractal
\psfractal[type=Mandel,xWidth=14cm,yWidth=12cm,maxIter=30,dIter=20] ( -2.5,-1.5)(1,1.5)
\end

The coordinates are a rectangle in the complex plane to draw, scaled up to xwidth,ywidth. More iterations with maxiter is higher resolution
but slower, diter is a scale factor for the colours. The pstricks-examples package which is samples from the PSTricks book includes similar
for LaTeX (25-02-6. ltx and 33-02-6. ltx).
Library: PGF
The PGF shadings library includes a Mandelbrot set. In PGF 3.0 the calculations are done in PostScript code emitted, so the output size is
small but it only does 10 iterations so is very low resolution.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shadings}
\begin{document}
\begin{tikzpicture}
\shade[shading=Mandelbrot set] (0,0) rectangle (4,4);
\end{tikzpicture}
\end{document}

Library: LuaTeX
LuaLaTeX plus pgfplots code can be found at http://texwelt.de/wissen/fragen/3960/fraktale-mit-pgfplots. The calculations are done by
inline Lua code and the resulting bitmap shown with a PGF plot.

TI-83 BASIC
Based on the BASIC Version. Due to the TI-83's lack of power, it takes around 2 hours to complete at 16 iterations.
PROGRAM:MANDELBR :Input "ITER. ",D :For(A,Xmin,Xmax,AX) :For(B,Ymin,Ymax,AY)
:0-X
:0->Y
:0-I
:D-M
:While XA2+YA2<4 and I<M
:XA2-YA2+A-R
:2XY+B-Y
:R->X
: I+1->I
:End
:If I*M
:Then :I->C
:Else
:0-C
:End
:If C<1
:Pt-0n(AJB)
:End
:End
:End

TXR
Translation of: Scheme Creates same mandelbrot.pgm file.
;(defvar x-centre -0.5)
Kdefvar y-centre 0.0)
!(defvar width 4.0)
!(defvar i-max 800)
Kdefvar j-max 600)
'(defvar n 100)
;(defvar r-max 2.0)
!(defvar file ,,mandelbrot.pgmH) Kdefvar colour-max 255) (defvar pixel-size (/ width i-max))

(defvar x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1)))) (defvar y-offset (+ ycentre (* 0.5 pixel-size (+ j-max 1))))
;; with-output-to-file macro
(defmacro with-output-to-file (name . body)
A
(let ((*stdout* (open-file ,name "w")))
(unwind-protect (progn ,*body) (close-stream *stdout*))))
;; complex number library (defmacro cplx (x y) A(cons ,x ,y)) (defmacro re (c)
A
(car ,c)) (defmacro im (c) A(cdr ,c))
http://rosetlacode.Org/wiki/M andel brot_set#MATLAB

70/78

19/11/2015

M andel brat set - Rosetta Code

(defsymacro c0 '(0 . 0)) (macro-time


(defun with-cplx-expand (specs body)
(tree-case specs
(((re im expr) . rest)
A

(tree-bind (,re . ,im) ,expr ,(with-cplx-expand rest body))) (() (tree-case body
((a b . rest) A(progn ,a ,b ,*rest))
((a) a)

(x (error "with-cplx: invalid body -s" body))))


(x (error "with-cplx: bad args ~s" x)))))
(defmacro with-cplx (specs . body)
(with-cplx-expand specs body))
(defun c+ (x y)
(with-cplx ((a b x) (c d y))
(cplx (+ a c) (+ b d))))
(defun c* (x y)
(with-cplx ((a b x) (c d y))
(cplx (- (* a c) (* b d)) (+ (* b c) (* a d)))))
(defun modulus (z)
(with-cplx ((a b z))
(sqrt (+ (* a a) (* b b)))))
;; Mandelbrot routines
(defun inside-p (z0 : (z c0) (n n))
(and (< (modulus z) r-max)
(or (zerop n)
(inside-p z (c+ (c* z z) z0) (- n 1)))))
(defmacro int-bool (b)
A
(if ,b colour-max 0))
(defun pixel (i j)
(int-bool
(inside-p
(cplx (+ x-offset (* pixel-size i))
(- y-offset (* pixel-size j))))))
;; Mandelbrot loop and output (defun plot ()
(with-output-to-file file
(format t ,,P2\n~s\n~s\n~s\n" i-max j-max colour-max) (each ((j
(range 1 j-max)))
(each ((i (range 1 i-max)))
(format *stdout* "~s " (pixel i j)))
(put-line "" *stdout*))))
(plot)

uBasic/4tH uBasic does not support floating point calculations, so fixed point arithmetic is used, with Value 10000 representing 1.0.
The Mandelbrot image is drawn using ASCII characters 1-9 to show number of iterations. Iteration count 10 or more is represented witb
@\ To compensate the aspect ratio of the font, step sizes in x and y directions are different.
ft =-21000
B = 15000
.C = 15000
D =-15000
E = 200
F = 350
G = 750

Left Edge = -2.1


1
Right Edge = 1.5
1
Top Edge - 1.5
1
Bottom Edge = -1.5
' Max Iteration Depth
' X Step Size
' Y Step Size

For L = C To D Step -G
For K = A To B-l Step F
V=0
U=0

' Y0
' X0
'Y
'X

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

71/78

19/11/2015

M andel brat set - Rosetta Code

i = 32

For 0 = 0 To E-l
X = (U/10 * U) / 1000
Y = (V/10 * V) / 1000 If (X + Y
> 40000)
I = 48 + 0 If
(0 > 9)
I = 64
Endif Break
Endif

Char To Be Displayed
Iteration
X*X
Y*Y
Print Digit 0...9 If Iteration Count
> 9, Print '@'

Z=X-Y+K

V = (U/10 * V) / 500 + L

Temp = X*X - Y*Y + X0 Y =


2*X*Y + Y0 X = Temp

u=z
Next
Gosub

Ins_char(I)

Next
Print
Next
End
Translate number to ASCII
32 Print " "
48 Print "0"

: Return
: Return

,49 Print "1"


50 Print "2"
51 Print "3"
52 Print "4"
53 Print "5"
54 Print "6"
55 Print "7"

: Return
: Return
: Return
: Return
: Return
: Return
: Return

56 Print "8"
57 Print "9"
64 Print "@"

: Return
: Return
: Return

Output:
1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211
1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222
1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222
1111111111111112222222222222333333333333333333333333333333333333322222222222222222222222222222222222222
1111111111111222222222233333333333333333333333344444457655544443333332222222222222222222222222222222222
1111111111112222222233333333333333333333333444444445567(3(36665444444333333222222222222222222222222222222
1111111111111222222222233333333333333333333333344444457655544443333332222222222222222222222222222222222

;111111122333333333333333333333444444455556@@@@@99@@@@
@@ jllllll2233333333333333333334444455555556678@@ @@
;illll22333333333333333334445555555555666789@@@
:illll23333333333333444466666555556666778@@@@
;illl23333333344444455568@887789@8777788@@@
|1111334444444455555567789@@
jllll4444444455555668@99@@@
;ill34555556666677789@@@ @ 1111
!lll34555556666677789@@@ @
jllll4444444455555668@99@@@
|llll334444444455555567789@@

@@@@

;illl23333333344444455568@887789@8777788@@@
;illll23333333333333444466666555556666778@@@@
;illll22333333333333333334445555555555666789@@@
1111112233333333333333333334444455555556678@@ @@
;111111122333333333333333333333444444455556@@@@@99@@@@
@@

@@@@76555544444333333322222222222222222222222
@987666555544433333333222222222222222222222
@@@@@@87777@95443333333322222222222222222222
@@@@@@@8544333333333222222222222222222
@86554433333333322222222222222222
@@87655443333333332222222222222222
@@@@65443333333332222222222222222
@@765444333333333222222222222222
@855444333333333222222222222222
@@655444433333333322222222222222
@86655444433333333322222222222222
@@876555444433333333322222222222222
@86655444433333333322222222222222
@@655444433333333322222222222222
@855444333333333222222222222222
@@765444333333333222222222222222
@@@@65443333333332222222222222222
@@87655443333333332222222222222222
@86554433333333322222222222222222
@@@@@@@8544333333333222222222222222222
@@@@@@87777@95443333333322222222222222222222
@987666555544433333333222222222222222222222
@@@@76555544444333333322222222222222222222222

1111111111111112222222222222333333333333333333333333333333333333322222222222222222222222222222222222222
1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222

1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222
1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211
1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
0 OK, 0:1726

Vedit macro language

http://rosetlacode.Org/wiki/M andel brot_set#MATLAB

72/78

19/11/2015

M andel brat set - Rosetta Code

Vedit macro language does not support floating point calculations, so fixed point arithmetic is used, with Value 10000 representing
1.0. Mandelbrot image is drawn using ASCII characters 1-9 to show number of iterations. Iteration count 10 or more is represented
with '@'. compensate the aspect ratio of the font, step sizes in x and y directions are different.
=-21000
j# = 15000
[#
2 = 15000
[#
3 =-15000
5
4 = 200
[# = 350
j#
6 = 750
7

// Left edge = -2.1

!#i

// right edge = 1 . 5
// top edge = 1 . 5

// bottom edge =

-1.5

// max iteration depth


// x step size
// y step size

[Bui _Switch(Buf_Free)

[for (#12 = #3; #12 > #4; #12 -= #7) {


for (#11 = # 1; #11 < #2; #11 += #6)
#22= 0

#21= 0
#9 1
for(#15 = 0; #15 < #5; #15++) {
#31 = (#21/10 * #21) / 1000
#32 = (#22/10 * #22) / 1000
if (#31 + #32 > 40000) {
#9 = '0' + #15
if (#15 > 9) {
#9 = '0'

//
//
//
//
//
//
//
//

ye

//
//
//

print digit 0.. .9


if iteration count > 93

xQ
y
x
char to be displayed
iteration
x*x

y*y

print '0

>

break
Ins Newline

}
// temp = x*x - y*y + x& // y = 2*x*y
+ yd // x = temp

#33 = #31 - #32 + #11 #22 =


(#21/10 * #22) / #21 = #33
>

Ins_Char(#9)

Output:
1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211
1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222

1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222
1111111111111112222222222222333333333333333333333333333333333333322222222222222222222222222222222222222
1111111111111222222222233333333333333333333333344444457655544443333332222222222222222222222222222222222

[111111122333333333333333333333444444455556@@@@@99@@@@
@@ [111111223333333333333333333444445555555667800 @0
>1111122333333333333333334445555555555666789000
[11111233333333333334444666665555566667780000
[111123333333344444455568088778908777788000
[111133444444445555556778900
[l1114444444455555668@99@@@
>111345 55556666677789@@@ 0
[111
[11134555556666677789@@@ 0
[11114444444455555668(399(300
[111133444444445555556778900

@000

111123333333344444455568088778908777788000
11111233333333333334444666665555566667780000
[1111122333333333333333334445555555555666789000
[111111223333333333333333333444445555555667800 @0
[111111122333 3333333333333333 3 344444445 5
55600000990@@@@@

@@@@76555544444333333322222222222222222222222
@987666555544433333333222222222222222222222
@@@@0087777095443333333322222222222222222222
00000008544333333333222222222222222222
@86554433333333322222222222222222
0087655443333333332222222222222222
@00065443333333332222222222222222
00765444333333333222222222222222
@855444333333333222222222222222
@0655444433333333322222222222222
@86655444433333333322222222222222
00876555444433333333322222222222222
@86655444433333333322222222222222
@0655444433333333322222222222222
@855444333333333222222222222222
@0765444333333333222222222222222
@@@@65443333333332222222222222222
@087655443333333332222222222222222
@86554433333333322222222222222222
00000008544333333333222222222222222222
@@@@@087777095443333333322222222222222222222
@987666555544433333333222222222222222222222
@@@@76555544444333333322222222222222222222222

1111111111111222222222233333333333333333333333344444457655544443333332222222222222222222222222222222222
1111111111111112222222222222333333333333333333333333333333333333322222222222222222222222222222222222222
1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222
1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222

1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211

XPLO

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

73/78

]J Y,
quit;
Y, Cnt21+Cnt<<10+Cnt<<3);
\setitfor
color
of
to
include c:\cxpl\codes;
X,
int [Point(X,
\intrinsic 'code' declarations
\\range:
rate
\screen
approached
-2.0
to pixel
+2.0
coordinates
\range:
infinity \move
-1.5
toontext
to next
\wait
keystroke
\restore
normal
X:=
Chln(l);
Cnt;
of current point \iteration
+1.5
counter
\initialize
\coordinates
\Z heads toward
point
];
display
19/11/2015
real Cx, Cy ]ZXj Zy Temp:= Zx*Zy;
scaled to +/-2 range \complex
infinity accumulator
M andel brat set - Rosetta Code
Setvid($03);
Temp; Zx:= Zx*Zx - Zy*Zy +\temporary
Cx; Zy:= scratch \calculate next iteration of Z
\set 640x480x24 graphics mode \for all
[SetVid($112);
2.0*Temp + Cy;
pointsnumber
on the screen...
for Y:= 0 to 480-1 doCnt:= Cnt+1;
\count
of iterations \assume point is in
for X:= 0 to 640-1
do >= 1000 then quit;
Mandelbrot \ set and leave it colored black
if Cnt
[Cx:= (float(X)/640.0 - 0.5) * 4.0;
];
Cy:= (float(Y-240)/240.0) * 1.5;
Cnt:= 0; Zx:= 0.0; Zy: = 0.0; loop [if Zx*Zx +
Zy*Zy > 2 . 0 then

Output:

XSLT
The fact that you can create an image of the Mandelbrot Set with XSLT is sometimes under-appreciated. However, it has been discussed
extensively on the internet (http://thedailywtf.com/Articles/Stupid-Coding-Tricks-XSLT-Mandelbrot.aspx) so is best reproduced here, and
the code can be executed directly in your browser at that site.

;<?xml version="1.0" encoding=MUTF-8"?>


|<xsl:stylesheet version="1.0,B xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

;
;

;<!-- XSLT Mandelbrot - written by loel Yliluoma 2007, http://iki.fi/bisqwit/ -->

!<xsl:output method="html indent=no"


;
doctype-public="-//W3C//DTD
HTML 4.01//EN"
;
doctype-system=http://www.w3.org/TR/REC-html40/strict.dtd

I
;
|

: />

:
M

!<xsl:template match="/fractal >


! <html>
;
<head>
;
<title>XSLT fractal</title>
!
<style type=Mtext/css">
Ibody { color:#55F; background:#000 }
Ipre { font-family:monospace; font-size:7px }
Ipre span { background:<xsl:value-of select="background"
;
</style>
1

l/hpad>

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

!
!
;
;
J

\
/> }

!
!
;
1

74/78

19/11/2015

M andel brat set - Rosetta Code

<body>
<div style=''position:absolute;top:20px; left: 20em">
Copyright 1992,2007 loel Yliluoma
(<a href="http://iki.fi/bisqwit/">http://iki.fi/bisqwit/</a>)
</div>
<hl style="margin:0px">XSLT fractal</hl>
<pre><xsl:call-template name=,,bisqwit-mandelbrotM /></pre>
</body>
</html>
</xsl:template>
<xsl:template name="bisqwit-mandelbrot"
xxsl:call-template name="bisqwit-mandelbrot-lineM>
<xsl:with-param name="y" select='ry/min"/>
</xsl:call-template ></xsl:template>
<xsl:template name="bisqwit-mandelbrot-line" xxslrparam name="y"
/xxsl:call-template name="bisqwit-mandelbrot-column">
<xsl:with-param name=x" select="x/minM/>
<xsl:with-param name=y select="$y"/>
</xsl:call-template xxsl:if test="$y < y/max"
Xbr
/xxsl:call-template name="bisqwit-mandelbrot-lineM>
<xsl:with-param name="y" select="$y + y/step"/>
</xsl:call-template x/xsl:if ></xsl:template>
<xsl:template name="bisqwit-mandelbrot-column"
><xsl:param name="x"
/xxsl:param name="y"
/Xxsl:call-template name="bisqwit-mandelbrot-slotM>
<xsl:with-param name=x" select="$x" />
<xsl:with-param name=y" select="$y" />
<xsl:with-param name="zr" select="$x" />
<xsl:with-param name="zi" select="$y" />
</xsl:call-template xxsl:if test="$x < x/max"
xxsl:call-template name="bisqwit-mandelbrot-columnM>
<xsl:with-param name="x" select="$x + x/step"/>
<xsl:with-param name="y" select="$y" />
</xsl:call-template ></xsl:if x/xsl:template>
<xsl:template name="bisqwit-mandelbrot-slot"
><xsl:param name=
/><xsl:param name="y"
/><xsl:param name="zr"
/><xsl:param name="zi"
/><xsl:param name="iter" select="0"
/Xxsl:variable name="zrsqr" select="($zr * $zr)"
/xxsl:variable name="zisqr" select="($zi * $zi)"
/><xsl:choose>
<xsl:when test="(4*scale*scale >= $zrsqr + $zisqr) and (maxiter > $iter+l)" xxsl:call-template
name=Mbisqwit-mandelbrot-slotM>
<xsl:with-param name="x select="$x" />
<xsl:with-param name="y" select="$y" />
<xsl:with-param name=,,zi" select="(2 * $zr * $zi) div scale + $y" /> <xsl:with-param name="zr"
select="($zrsqr - $zisqr) div scale + $x" /> <xsl:with-param name="iterM select="$iter + 1" />
</xsl:call-template ></xsl:when>
<xsl:otherwise
xxsl:variable name="magnitude" select="magnitude[@value=$iter]"
/Xspan style=ncolor:{$magnitude/color}" xxsl:value-of
select="$magnitude/symbol"
/x/spanx/xsl: otherwise>
</xsl:choose x/xsl:template>
</xsl:stylesheet>

Z80 Assembly

j; Compute a MandeLbrot set on a simple Z80 computer.


J; Porting this program to another Z80 platform should be easy and straight- \j forward: The only
dependencies on my homebrew machine are the system-calls I; used to print strings and characters. These
calls are performed by loading j; IX with the number of the system-call and performing an RST 08. To port
this

http://rosetlacode.org/wiki/M andel brot_set#M ATLAB

75/78

19/11/2015

M andel brat set - Rosetta Code

program to another operating system just rep Lace these system-caLLs with ; the appropriate versions. OnLy three system-caLLs are used in the following: y _crif: Prints a CR/LFj _puts: Prints a 6-terminated
string (the adress of
\; which is expected in HL), and putc: Print a
single character which is
give control back to the monitor.
1; expected in A. RST 0
IJ

!#include

"mondef.asm"
org

ram_start

[scale

equ

256

Idivergent

equ

scale * 4

Id
Id
rst

hi, welcome
iXj _puts

for (x
{

= x_start;

hi, (x start)
(x), hi
hi, (x_end)
de, (x)
a
hi, de
m, inner_loop_end

JP
\> z-0

= z_l = 0;
Id
Id
Id

Id
Id

a, (iteration_max)
b, a
be
0 - Z_1 * z_l) / SCALE;
de, (z_l)
be, de
mul_16
(z_0_square_low), hi
(z_0_square_high), de

de, (z_0)

Id
Id
call
Id
Id

be, de
mul_16
(z_l_square_low), hi
(z_l_square_high), de

; x = x_start
; Is x <= x_end?

; End of inner loop reached

; iteration -> stack


; Compute DE HL = z_l * z_l

. z_0 ** 2 is needed Later again

; Compute DE HL = z_0 * z_0

. z l ** 2

be aL5Q

and
Id
sbc

a
be, (z 0 square low)
hi, be

; Compute subtraction

Id
Id
Id
sbc
Id

(scratch 0), hi
hi, de
be, (z_0_square_high)
hi, be
be, (scratch_0)

; Save lower 16 bit of result

c, b
b, 1
be

Id
Id
push

needed

; HL BC = z_0 ** 2 - z_l ** 2

;
;

Divide by scale = 256


Discard the rest
We need BC Later

z3
= 2 * z0 *

zl / SCALE;
hi, (z_0)
hi, hi

Id
add
Id
Id
call

Zl

b, e
c, h

z3 + y;
Id
add
Id

_0 = z

pop
Id

; Compute

DE HL = 2

z_0 * z_l

de, hi
be, (z_l)
mul_16

Id
Id
u

; Clear carry
; Perform the comparison
; End of outer loop reached

iteration_max; iteration; iteration--)

!iteration_loop push
u
z2 = (z_0 * z_
Id
Id
call
Id
Id

i;

; Is y <= y_end?

hi, 0
(z_0), hi
(z_l), hi

for(iteration

.step)

x <= x_end; x += x_step)

Id
Id
Id
Id
and
sbc

iinner_loop

; Print a welcome message

08

for (y =<initial_value> ; y <= y_end; y += y_


V<
jouterloop
Id
hi, (y_end)
Id
de* (y)
and
a
sbc
hi, de
m, mandel_end
jP
'j
J

; Do NOT change this - the


; arithmetic routines rely on
; this scaling factor! :-)

Divide by scale ( = 256)


contains now z_3

; BC

hi, (y)
hi, be
(z_l), hi
X j

be
hi, (x)

http://rosettacode.org/wiki/M andel brot_set#M ATLAB

Here BC is needed again : - )

76/78

19/11/2015

M andel brat set - Rosetta Code


add
Id

if (Z0

(z_0), hi

* z0 / SCALE + zl * zl / SCALE
Id
hi, (z_0_square_low)
Id
de, (z_l_square_low)
add
hi, de
Id
be, hi
Id
Id
adc

hi, (z_0_square_high)
de, (z_l_square_high)
hi, de

Id
Id

h, 1
1, b

Id
and
sbc

be, divergent
a
hi, be

break;
jp
pop
jr

hi, be

c, iteration_dec
be
iteration_end

> 4 * SCALE)
; Use the squares computed
; above
; BC contains Lower word of sum

; HL now contains (z_0 ** 2 +


; z_l ** 2) / scale

; No break
; Get latest iteration counter
; Exit loop

iteration++;

iteration_dec

pop

be

djnz

iteration_loop

j Get iteration counter


; We might fall through!

;>
iteration_end

printf("%c 3 display [iteration % 7]);


Id
a, b
$7
and
sbc
hi, hi
Id
1, a
Id
de, display
add
hi, de
Id
a, (hi)
Id
ix, _putc
rst
08

; Lower three bits only (c = 0)

; Get start of character array


; address and load the
; character to be printed
; Print the character

Id
Id
add
Id

de, (x step)
hi, (X)
hi, de

; x += x_step

jP

inner_loop

Id
rst

ix, _crlf

Id
Id
add
Id

de, (y_step)
hi, (y)
hi, de
(y), hi

jP

outerloop

Id
Id
rst

hi, finished
ix, _puts

rst

defb
defb
defb

"Generating a Mandelbrot set"


cr, If, eos
"Computation finished."
, cr, If, eos

(x), hi

*}

J printf("\n");
inner_loop_end

; Print a CR/LF pair

08
; y += y_step

; Store new y-value

< y
nandel_end

welcome
finished

iteration_max
defb
X
defw
x_start
defw
|x_end
defw
x_step
defw
y
defw
y_end
defw
y_step
defw
z_0
defw
z 1
defw
scratch_0
defw
z_0_square_high defw
z_0_square_low
defw
z_l_square_high
defw
z_l_square_low
defw
display
defb

; Print finished-message

08

10
0
-2 * scale
5 * scale / 10
4 * scale / 100
-1 * scale
1 * scale
1 * scale / 10

0
0
0
0
0
0
0
" .-+*=#@"

; Return to the monitor

; How many iterations


; x-coordinate
; Minimum x-coordinate
; Maximum x-coordinate
; x-coordinate step-width
; Minimum y-coordinate

; Maximum y-coordinate
; y-coordinate step-width

; 8 characters for the display

Compute DEHL = BC * DE (signed): This routine is not too cLever but it j; works. It is based on
a standard 16-by-16 multiplication routine for unsigned integers. At the beginning the sign of the
result is determined based on the
http://rosettacode.org/wiki/M andel brot_set#M ATLAB

77/78

19/11/2015

M andel brat set - Rosetta Code

signs of the operands which are negated if necessary. Then the unsigned
multiplication takes place, foLLowed by
negating the result if necessary.

.
i*

ynul_16

bc_positive

de_positive

jnul_16_loop

xor
bit
jr
sub
Id
Id
sbc
Id
scf
bit

a
7, b
z, bcpositive

c
C, a

,* Clear carry and A (-> +)


; Is BC negative?
; No
; A is still zero, complement

a, 0

b
b, a

7, D
z, de_positive
af

push
xor
sub
Id
Id
sbc
Id
pop
ccf
push
and
sbc
Id
add
rl
rl

; Set carry (-> -)


; Is DE negative?
; No
; Remember carry for later!

a
e
e, a
a, 0
a, d
d, a
; Restore carry for complement
; Complement Carry (-> +/-?)
; Remember state of carry
; Start multiplication

af
af

a
hi, hi

; 16 rounds

a, 16

hi, hi
e
d
nc, mul_16_exit

}nul_16_exit

add
jr
inc
dec

hi, be
nc, mul_16_exit

de
a
nz, mul_16_loop
af
nc

pop
ret
xor
sub
Id
Id
sbc
Id
Id
sbc
Id
Id
sbc
Id
ret

a
1
1, a
a, 0
a, h
h, a

; Restore carry from beginning


; No sign inversion necessary
; Complement DE HL

a, 0

a, e
e, a
a, 0
a, d
d, a

Output
:
iGenerating a Mandelbrot set
*######$@@@@ *===#####@@@@
!

+*====####@@ .~+

****_l_*0 -=#
===**+= *** + _

+*******++++_
@@@@#######===**~

@@#######======++#######=****+-

@#######=====*-~~ @@@########====*++.

@@@@@@@######==*+
- + * = *##

.-+**====###@
.+*=######@@@@0

[Computation finished.

zkl
Uses the PPM class from http://rosettacode.Org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl

Translation of: XPLO http://rosettacode.Org/wiki/M andel brot_set#M ATLAB


77/78

19/11/2015

M andel brat set - Rosetta Code

rfcn mandelbrot{ // lord this is slooooow ;


bitmap:=PPM(640,480);
; foreach y,x in ([0..479]3[0..639]){
!
cx:=(x.toFloat()/640 - 0.5)*4.0;
//range: -2.0 to +2.0
I
cy:=((y-240).toFloat()/240.0)*1.5; //range: -1.5 to +1.5
!
cnt:=0; zx:=0.0; zy:=0.0;
|
do(1000){
;
if(zx*zx + zy*zy > 2.0){
//z heads toward infinity
;
//set color of pixel to rate it approaches infinity
;
bitmap[x,y]=cnt.shiftLeft(21) + cnt.shiftLeft(10) + cnt*8;
!
break;
;
}
i
temp:=zx*zy;
;
zx=zx*zx - zy*zy + cx;
//calculate next iteration of z
;
zy=2.0*temp
+cy;
!
cnt+=l;
:

;}
i

bitmap.write(File(foo.ppm", "wb));

Output:
Same as the XPLO image: http://www.zenkinetic.com/Images/RosettaCode/mandelbrot.jpg
Retrieved from "http://rosettacode.org/mw/index.php?title=Mandelbrot_set&oldid=216460"
Categories: WikipediaSourced Programming Tasks Fractals Graphics Raster graphics operations ACL2 Ada Lumen ALGOL 68 Applesoft BASIC
AutoHotkey AWK BASIC BASIC256 BBC BASIC Liberty BASIC OS/8 BASIC Run BASIC Small BASIC Befunge Brace Brainf*** C GLUT C++ C sharp
Clojure D QD SDL Phobos Dart DEC BASIC-PLUS DWScript Erlang ERRE F Sharp Forth Fortran GLSL Gnuplot Go Haskell Haxe Icon Unicon Icon
Programming Library Unicon examples needing attention Examples needing attention IDL Inform 7 Glimmr Drawing Commands by Erik Temple J Java
Swing AWT JavaScript Jq Julia Lab VIEW Lang5 Lasso Logo Mathematica Wolfram Language MATLAB Modula-3 MySQL Nim OCaml Octave Pascal
Perl Perl 6 Phix PHP GD Graphics Library PicoLisp PostScript Prolog PureBasic Python Matplotlib Numpy R Racket REXX Ruby Scala Scheme Scratch
Sass/SCSS Seed7 Sidef Tel Tk TeX Pst-fractal PGF LuaTeX TI-83 BASIC TXR UBasic/4tH Vedit macro language XPLO XSLT M4/Omit Z80 Assembly
Zkl Lilypond/Omit ML/I/Omit Geometry

This page was last modified on 18 November 2015, at 19:00.


Content is available under GNU Free Documentation License 1.2.

http://rosetlacode.Org/wiki/M andel brot_set#MATLAB

79/78

You might also like