Mandelbrot set: Difference between revisions

Convert <lang> elements to <syntaxhighlight>
m (Remove unused import.)
(Convert <lang> elements to <syntaxhighlight>)
Line 13:
{{trans|Python}}
 
<langsyntaxhighlight lang=11l>F mandelbrot(a)
R (0.<50).reduce(0i, (z, _) -> z * z + @a)
 
Line 20:
 
V rows = (step(1, -0.05, 41).map(y -> (step(-2.0, 0.0315, 80).map(x -> (I abs(mandelbrot(x + 1i * @y)) < 2 {‘*’} E ‘ ’)))))
print(rows.map(row -> row.join(‘’)).join("\n"))</langsyntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight lang=Lisp>(defun abs-sq (z)
(+ (expt (realpart z) 2)
(expt (imagpart z) 2)))
Line 77:
(defun draw-mandelbrot (width iters)
(let ((height (floor (* 1000 width) 3333)))
(draw-mandel 1 height width height iters)))</langsyntaxhighlight>
 
{{out}}
Line 103:
{{libheader|Lumen}}
mandelbrot.adb:
<langsyntaxhighlight lang=Ada>with Lumen.Binary;
package body Mandelbrot is
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is
Line 142:
end Create_Image;
 
end Mandelbrot;</langsyntaxhighlight>
 
mandelbrot.ads:
<langsyntaxhighlight lang=Ada>with Lumen.Image;
 
package Mandelbrot is
Line 151:
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;
 
end Mandelbrot;</langsyntaxhighlight>
 
test_mandelbrot.adb:
<langsyntaxhighlight lang=Ada>with System.Address_To_Access_Conversions;
with Lumen.Window;
with Lumen.Image;
Line 308:
when Program_End =>
null;
end Test_Mandelbrot;</langsyntaxhighlight>
 
{{out}}
Line 318:
Plot part of the Mandelbrot set as a pseudo-gif image.
 
<langsyntaxhighlight lang=algol68>
INT pix = 300, max iter = 256, REAL zoom = 0.33 / pix;
[-pix : pix, -pix : pix] INT plane;
Line 357:
OD;
close (plot)
</syntaxhighlight>
</lang>
 
=={{header|ALGOL W}}==
Generates an ASCII Mandelbrot Set. Translated from the sample program in the Compiler/AST Interpreter task.
<langsyntaxhighlight lang=algolw>begin
% This is an integer ascii Mandelbrot generator, translated from the %
% Compiler/AST Interpreter Task's ASCII Mandelbrot Set example program %
Line 400:
end for_y0
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 452:
 
Hopper-code & macros Version:
<langsyntaxhighlight lang=Amazing Hopper>
#!/usr/bin/hopper
 
Line 501:
{mandel,"mandel.dat"}save
{0}return
</syntaxhighlight>
</lang>
 
Hopper-Basic high level language version:
<langsyntaxhighlight lang=Amazing Hopper>
#!/usr/bin/hopper
 
Line 552:
{mandel,"mandel.dat"}save
{0}return
</syntaxhighlight>
</lang>
 
 
Line 559:
{{trans|Nim}}
 
<langsyntaxhighlight lang=rebol>inMandelbrot?: function [c][
z: to :complex [0 0]
do.times: 50 [
Line 586:
mandelbrot #[ yStart: 1.0 yStep: neg 0.05
xStart: neg 2.0 xStep: 0.0315
height: 40 width: 80 ]</langsyntaxhighlight>
 
{{out}}
Line 627:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=autohotkey>Max_Iteration := 256
Width := Height := 400
 
Line 743:
;---------------------------------------------------------------------------
Return, (r&0xFF)<<16 | g<<8 | b
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang=AWK>BEGIN {
XSize=59; YSize=21;
MinIm=-1.0; MaxIm=1.0;MinRe=-2.0; MaxRe=1.0;
Line 767:
}
exit;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 796:
This implements a 16bit fixed point arithmetic Mandelbrot set calculation.
{{works with|The Amsterdam Compiler Kit - B|V6.1pre1}}
<langsyntaxhighlight lang=B>main() {
auto cx,cy,x,y,x2,y2;
auto iter;
Line 838:
 
return(0);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 873:
{{trans|QBasic}}
 
<langsyntaxhighlight lang=amigabasic>SCREEN 1,320,200,5,1
WINDOW 2,"Mandelbrot",,0,1
 
Line 920:
' endless loop, use Run -> Stop from the menu to stop program
WHILE (1)
WEND</langsyntaxhighlight>
==={{header|Applesoft BASIC}}===
 
This version takes into account the Apple II's funky 280&times;192 6-color display, which has an effective resolution of only 140&times;192 in color.
 
<langsyntaxhighlight lang=basic>
10 HGR2
20 XC = -0.5 : REM CENTER COORD X
Line 962:
330 NEXT YS
340 NEXT YI
</syntaxhighlight>
</lang>
 
By making the following modifications, the same code will render the Mandelbrot set in monochrome at full 280&times;192 resolution.
 
<langsyntaxhighlight lang=basic>
150 FOR XS = 0 TO 279
301 C = (C - INT(C/2)*2)*3
310 HCOLOR = C: HPLOT XS, YS
</syntaxhighlight>
</lang>
 
 
Line 978:
This can be run in BeebEm. Select BBC model as Master 128 with ARM Second Processor. Load disc armdisc3.adl and switch to ADFS. At the prompt load ARM Basic by running the AB command.
 
<langsyntaxhighlight lang=bbcbasic>
10MODE5:VDU5
20D%=100 : REM adjust for speed/precision
Line 988:
70PLOT69,X%,Y%
80NEXT
90NEXT</langsyntaxhighlight>
[[File:Mandelbrot_armbasic.png]]
 
==={{header|BASIC256}}===
 
<langsyntaxhighlight lang=basic-256>fastgraphics
 
graphsize 384,384
Line 1,027:
next x
imgsave "Mandelbrot_BASIC-256.png", "PNG"
</syntaxhighlight>
</lang>
{{out|Image generated by the script}}
[[File:Mandelbrot BASIC-256.jpg|220px]]
Line 1,033:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang=bbcbasic> sizex% = 300 : sizey% = 300
maxiter% = 128
VDU 23,22,sizex%;sizey%;8,8,16,128
Line 1,054:
PLOT X%,Y% : PLOT X%,-Y%
NEXT
NEXT X%</langsyntaxhighlight>
[[File:Mandelbrot_bbc.gif]]
 
==={{header|Commander X16 BASIC}}===
 
<langsyntaxhighlight lang=X16BASIC>
10 CLS
20 SCREEN $80
Line 1,080:
190 PSET X,YR,I
200 :NEXT:NEXT
</syntaxhighlight>
</lang>
 
==={{header|Commodore BASIC}}===
Line 1,090:
Runs in about 90 minutes.
 
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 COLOR 1,3,0,0:GRAPHIC 2:TH=20
120 FOR PY=0 TO 80
Line 1,110:
280 NEXT PY
290 GET K$:IF K$="" THEN 290
300 GRAPHIC 4</langsyntaxhighlight>
 
===={{header|C-64 with Super Expander 64}}====
Runs in about 4.5 hours.
 
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 COLOR 6,0,0,0,6:GRAPHIC 2,1
120 FOR PY=0 TO 100
Line 1,133:
280 NEXT PY
290 GET K$:IF K$="" THEN 290
300 GRAPHIC 0</langsyntaxhighlight>
 
===={{header|Commodore-16 / 116 / Plus/4}}====
{{works with|Commodore BASIC|3.5}}
Despite the faster clock on the TED systems compared to the C-64, this takes almost six hours to run.
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 COLOR 0,2:COLOR 1,1:GRAPHIC 1,1
120 FOR PY=0 TO 100
Line 1,155:
250 NEXT PY
260 GETKEY K$
270 GRAPHIC 0</langsyntaxhighlight>
 
===={{header|Commodore 128 (40-column display)}}====
Line 1,164:
64 and Plus/4 versions.
 
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 COLOR 0,12:GRAPHIC 1,1:COLOR 1,1:GRAPHIC0:FAST
120 FOR PY=0 TO 100
Line 1,182:
260 SLOW:GRAPHIC 1
270 GETKEY K$
280 GRAPHIC 0</langsyntaxhighlight>
 
===={{header|Commodore 128 (80-column display)}}====
Line 1,189:
This uses BASIC 8 to create a 640x200 render on the C-128's 80-column display. The doubled resolution comes with a commensurate increase in run time; this takes about 5h20m using FAST 2MHz mode.
 
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 @MODE,0:@COLOR,15,0,0:@SCREEN,0,0:@CLEAR,0:FAST
120 FOR PY=0 TO 100
Line 1,207:
250 NEXT PY
260 GETKEY K$
270 @TEXT</langsyntaxhighlight>
 
{{Out}}
Line 1,215:
===={{header|Commodore PET}}====
Here's a version using mostly ASCII and some PETSCII (could probably improve the tile set for PETSCII) inspired by the Perl solution. Designed for a PET with an 80-column display.
<langsyntaxhighlight lang=basic>100 TH=20:REM ESCAPE THRESHOLD IN ITERATIONS
110 CH$=" .:-=+*#@"+CHR$(255)
120 FOR Y=1 TO -1 STEP -0.08
Line 1,234:
270 NEXT I
280 IF I>TH THEN I=TH
290 RETURN</langsyntaxhighlight>
 
{{Out}} VICE screenshot [https://i.imgur.com/y4zYmyD.png here].
Line 1,257:
160 NEXT Y
170 END
</syntaxhighlight>
</lang>
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,283:
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang=freebasic>#define pix 1./120
#define zero_x 320
#define zero_y 240
Line 1,338:
while inkey=""
wend
end</langsyntaxhighlight>
 
==={{header|GW-BASIC}}===
<langsyntaxhighlight lang=gwbasic>10 SCALE# = 1/60 : ZEROX = 160
20 ZEROY = 100 : MAXIT = 32
30 SCREEN 1
Line 1,360:
180 PSET (X, 2*ZEROY-Y), 1+(I MOD 3)
190 NEXT Y
200 NEXT X</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
Any words of description go outside of lang tags.
<langsyntaxhighlight lang=lb>nomainwin
 
WindowWidth =440
Line 1,419:
close #w
end
</syntaxhighlight>
</lang>
 
==={{header|Locomotive Basic}}===
{{trans|QBasic}}
This program is meant for use in [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic] specifically, where it draws a 16-color 640x400 image in less than a minute. (Real CPC hardware would take far longer than that and has lower resolution.)
<langsyntaxhighlight lang=locobasic>1 MODE 3 ' Note the CPCBasic-only screen mode!
2 FOR xp = 0 TO 639
3 FOR yp = 0 TO 399
Line 1,440:
15 PLOT xp, yp, c MOD 16
16 NEXT
17 NEXT</langsyntaxhighlight>
 
==={{header|Microsoft Small Basic}}===
<langsyntaxhighlight lang=Small BASIC>
GraphicsWindow.Show()
size = 500
Line 1,473:
EndFor
EndFor
</syntaxhighlight>
</lang>
 
==={{header|Microsoft Super Extended Color BASIC (Tandy Color Computer 3)}}===
 
<langsyntaxhighlight lang=COCO3BASIC>
1 REM MANDELBROT SET - TANDY COCO 3
2 POKE 65497,1
Line 1,498:
170 NEXT Y
180 GOTO 180
</syntaxhighlight>
</lang>
 
==={{header|Nascom BASIC}}===
Line 1,508:
Only a fragment of the shape is drawn because of low resolution of block graphics. Like in the ZX81 version, you can adjust the constants in lines 40 and 70 to zoom in on a particular area, if you like.
{{works with|Nascom ROM BASIC|4.7}}
<langsyntaxhighlight lang=basic>
10 REM Mandelbrot set
20 CLS
Line 1,547:
510 DATA 27085,14336,-13564,6399,18178,10927
520 DATA -8179,233
</syntaxhighlight>
</lang>
 
==={{header|OS/8 BASIC}}===
Works under BASIC on a PDP-8 running OS/8. Various emulators exist including simh's PDP-8 emulator and the [http://www.bernhard-baehr.de/pdp8e/pdp8e.html PDP-8/E Simulator] for Classic Macintosh and OS X.
<langsyntaxhighlight lang=qbasic>10 X1=59\Y1=21
20 I1=-1.0\I2=1.0\R1=-2.0\R2=1.0
30 S1=(R2-R1)/X1\S2=(I2-I1)/Y1
Line 1,567:
150 PRINT
160 NEXT Y
170 END</langsyntaxhighlight>
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,594:
==={{header|PureBasic}}===
PureBasic forum: [http://www.purebasic.fr/german/viewtopic.php?f=4&t=22107 discussion]
<langsyntaxhighlight lang=PureBasic>EnableExplicit
 
#Window1 = 0
Line 1,651:
Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
EndIf</langsyntaxhighlight>Example:<br>
[[File:Mandelbrot-PureBasic.png]]
 
Line 1,657:
This is almost exactly the same as the pseudocode from [[wp:Mandelbrot set#For_programmers|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.
 
<langsyntaxhighlight lang=qbasic>SCREEN 13
WINDOW (-2, 1.5)-(2, -1.5)
FOR x0 = -2 TO 2 STEP .01
Line 1,684:
PSET (x0, y0), c + 32
NEXT
NEXT</langsyntaxhighlight>
==={{header|Quite BASIC}}===
<langsyntaxhighlight lang=Quite BASIC>
1000 REM Mandelbrot Set Project
1010 REM Quite BASIC Math Project
Line 1,731:
3090 LET P[8] = "white"
3100 RETURN
</syntaxhighlight>
</lang>
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang=Runbasic>'Mandelbrot V4 for RunBasic
'Based on LibertyBasic solution
'copy the code and go to runbasic.com
Line 1,824:
print "All done, good bye."
end
</syntaxhighlight>
</lang>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 1,831:
 
Glacially slow, but does eventually produce a tolerable low-resolution image (screenshot [http://edmundgriffiths.com/zxmandelbrot.jpg here]). You can adjust the constants in lines 30 and 40 to zoom in on a particular area, if you like.
<langsyntaxhighlight lang=zxbasic> 10 FOR I=0 TO 63
20 FOR J=43 TO 0 STEP -1
30 LET X=(I-52)/31
Line 1,845:
130 IF ITER=200 THEN PLOT I, J
140 NEXT J
150 NEXT I</langsyntaxhighlight>
 
==={{Header|SmileBASIC}}===
 
Generates the points at random, gradually building up the image.
<langsyntaxhighlight lang=smilebasic>X = RNDF()*4-2
Y = RNDF()*4-2@N
N = N+16
Line 1,858:
IF N < #L&&S*S+T*T < 4 GOTO @N
GPSET X*50+99, Y*50+99, RGB(99 XOR N,N,N)
EXEC.</langsyntaxhighlight>
 
Alternative, based on the QBasic and other BASIC samples.
<br>
The 3DS screen is 400 x 240 pixels. SmileBASIC doesn't have +=, -=, etc. but there are INC and DEC statements.
<langsyntaxhighlight lang=basic>OPTION STRICT
VAR XP, YP, X, Y, X0, Y0, X2, Y2
VAR NEXT_X, IT, C
Line 1,882:
GPSET XP + 200, YP + 120, RGB((C * 3) MOD 200 + 50, FLOOR(C * 1.2) + 20, C)
NEXT
NEXT</langsyntaxhighlight>
 
==={{header|TI-Basic Color}}===
{{works with|TI-84 Plus CSE, TI-83 Premium CE, TI-84 Plus CE}}
<langsyntaxhighlight lang=TI-BASIC>
ClrDraw
~2->Xmin:1->Xmax:~1->Ymin:1->Ymax
Line 1,902:
End
End
</syntaxhighlight>
</lang>
 
==={{header|Visual BASIC for Applications on Excel}}===
{{works with|Excel 2013}}
Based on the BBC BASIC version. Create a spreadsheet with -2 to 2 in row 1 and -2 to 2 in the A column (in steps of your choosing). In the cell B2, call the function with =mandel(B$1,$A2) and copy the cell to all others in the range. Conditionally format the cells to make the colours pleasing (eg based on values, 3-color scale, min value 2 [colour red], midpoint number 10 [green] and highest value black. Then format the cells with the custom type "";"";"" to remove the numbers.
<langsyntaxhighlight lang=VBA>
Function mandel(xi As Double, yi As Double)
 
Line 1,923:
mandel = i
End Function
</syntaxhighlight>
</lang>
[[File:vbamandel.png]]
Edit: I don't seem to be able to upload the screenshot, so I've shared it here: https://goo.gl/photos/LkezpuQziJPAtdnd9
 
==={{header|Yabasic}}===
<langsyntaxhighlight lang=Yabasic>open window 640, 320
wid = 4
xcenter = -1: ycenter = 0
Line 1,964:
next ycoord
next xcoord
</syntaxhighlight>
</lang>
 
=={{header|Befunge}}==
Line 1,971:
X scale is (-2.0, 0.5); Y scale is (-1, 1); Max iterations 94 with the ASCII character set as the "palette".
 
<langsyntaxhighlight lang=Befunge>0>:00p58*`#@_0>:01p78vv$$<
@^+1g00,+55_v# !`\+*9<>4v$
@v30p20"?~^"< ^+1g10,+*8<$
Line 1,981:
>*%03 p58*:*/01g"3"* v>::^
\_^#!:-1\+-*2*:*85<^
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,028:
=={{header|Brace}}==
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.d/1
<langsyntaxhighlight lang=brace>#!/usr/bin/env bx
use b
 
Line 2,044:
w = w*w + c
*px++ = i < max_i ? rainbow(i*359 / rb_i % 360) : black
c += d</langsyntaxhighlight>
 
An example plot from the longer version:
Line 2,051:
 
=={{header|Brainf***}}==
<langsyntaxhighlight lang=Brainf***>
A mandelbrot set fractal viewer in brainf*ck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
Line 2,197:
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,253:
===PPM non interactive===
Here is one file program. It directly creates ppm file.
<langsyntaxhighlight lang=C> /*
c program:
--------------------------------
Line 2,342:
fclose(fp);
return 0;
}</langsyntaxhighlight>
 
===PPM Interactive===
Line 2,351:
 
{{libheader|GLUT}}
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 2,590:
glutMainLoop();
return 0;
}</langsyntaxhighlight>
 
===ASCII===
Not mine, found it on Ken Perlin's homepage, this deserves a place here to illustrate how awesome C can be:
<syntaxhighlight lang=C>
<lang C>
main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x
=0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0;
j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);}
</syntaxhighlight>
</lang>
There may be warnings on compiling but disregard them, the output will be produced nevertheless. Such programs are called obfuscated and C excels when it comes to writing such cryptic programs. Google IOCCC for more.
<pre>
Line 2,635:
 
===Fixed point 16 bit arithmetic===
<syntaxhighlight lang=C>
<lang C>
/**
ascii Mandelbrot using 16 bits of fixed point integer maths with a selectable fractional precision in bits.
Line 2,738:
 
 
</syntaxhighlight>
</lang>
 
<pre>
Line 2,813:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Drawing;
using System.Drawing.Imaging;
Line 2,950:
return Re * Re + Im * Im;
}
}</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang=cpp>#include <cstdlib>
#include <complex>
 
Line 2,992:
 
}
}</langsyntaxhighlight>
 
Note this code has not been executed.
Line 2,999:
<br>
A Simple version in CPP. Definitely not as crazy good as the ASCII one in C above.
<langsyntaxhighlight lang=cpp>#include <stdio.h>
 
int f(float X, float Y, float x, float y, int n){
Line 3,009:
for(float i=-2, x; i<=.5; i+=.015, x=f(i, j, 0, 0, 0))
printf("%c%s", x<10?' ':x<20?'.':x<50?':':x<80?'*':'#', i>-2?" ":"\n");
}</langsyntaxhighlight>
 
=={{header|C3}}==
This program produces a BMP as output.
<langsyntaxhighlight lang=c3>module mandelbrot;
 
extern fn int atoi(char *s);
Line 3,070:
}
}
}</langsyntaxhighlight>
 
=={{header|Cixl}}==
Displays a zooming Mandelbrot using ANSI graphics.
 
<langsyntaxhighlight lang=cixl>
use: cx;
 
Line 3,145:
#out show-cursor
normal-mode
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
{{trans|Perl}}
<langsyntaxhighlight lang=lisp>(ns mandelbrot
(:refer-clojure :exclude [+ * <])
(:use (clojure.contrib complex-numbers)
Line 3,170:
 
(println (interpose \newline (map #(apply str %) (partition 80 (mandelbrot)))))
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
EBCDIC art.
<langsyntaxhighlight lang=cobol>IDENTIFICATION DIVISION.
PROGRAM-ID. MANDELBROT-SET-PROGRAM.
DATA DIVISION.
Line 3,224:
ADD X-A-SQUARED TO Y-A-SQUARED GIVING SUM-OF-SQUARES.
MOVE FUNCTION SQRT (SUM-OF-SQUARES) TO ROOT.
IF ROOT IS GREATER THAN 2 THEN MOVE '#' TO PLOT-CHARACTER.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,253:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(defpackage #:mandelbrot
(:use #:cl))
 
Line 3,297:
for pixel = (round (* 255 (/ (- *iteration-max* iteration) *iteration-max*)))
do (setf (aref image y x) pixel)))
(write-pgm image filespec)))</langsyntaxhighlight>
 
=={{header|Cowgol}}==
{{trans|B}}
<langsyntaxhighlight lang=cowgol>include "cowgol.coh";
 
const xmin := -8601;
Line 3,335:
print_nl();
cy := cy + dy;
end loop;</langsyntaxhighlight>
{{out}}
<pre>!!!!!!!!!!!!!!!"""""""""""""####################################""""""""""""""""
Line 3,365:
===Textual Version===
This uses <code>std.complex</code> because D built-in complex numbers are deprecated.
<langsyntaxhighlight lang=d>void main() {
import std.stdio, std.complex;
 
Line 3,377:
writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>.......................................................................................
Line 3,431:
===More Functional Textual Version===
The output is similar.
<langsyntaxhighlight lang=d>void main() {
import std.stdio, std.complex, std.range, std.algorithm;
 
Line 3,438:
.recurrence!((a, n) => a[n - 1] ^^ 2 + complex(x, y))
.drop(100).front.abs < 2 ? '#' : '.').writeln;
}</langsyntaxhighlight>
 
===Graphical Version===
{{libheader|QD}} {{libheader|SDL}} {{libheader|Phobos}}
<langsyntaxhighlight lang=d>import qd;
 
double lensqr(cdouble c) { return c.re * c.re + c.im * c.im; }
Line 3,468:
}
while (true) { flip; events; }
}</langsyntaxhighlight>
 
=={{header|Dart}}==
Line 3,508:
print(line);
}
}</langsyntaxhighlight>
 
=={{header|Dc}}==
Line 3,517:
This can be done in a more Dc-ish way, e.g. by moving the loop macros' definitions to the initialisations in the top instead of saving the macro definition of inner loops over and over again in outer loops.
 
<langsyntaxhighlight lang=dc> _2.1 sx # xmin = -2.1
0.7 sX # xmax = 0.7
 
Line 3,585:
l2 x # loop
] s2
l2 x</langsyntaxhighlight>
{{out}}
<pre>
Line 3,617:
===PGM (P5) output===
This is a condensed version of the ASCII output variant modified to generate a PGM (P5) image.
<langsyntaxhighlight lang=dc>_2.1 sx 0.7 sX _1.2 sy 1.2 sY
32 sM
640 sW 480 sH
Line 3,653:
l2 x
] s2
l2 x</langsyntaxhighlight>
 
 
Line 3,660:
=={{header|DWScript}}==
{{trans|D}}
<langsyntaxhighlight lang=delphi>const maxIter = 256;
 
var x, y, i : Integer;
Line 3,676:
end;
PrintLn('');
end;</langsyntaxhighlight>
 
=={{header|EasyLang}}==
Line 3,701:
rect 0.4 0.4
.
.</langsyntaxhighlight>
 
=={{header|eC}}==
Line 3,709:
 
Drawing code:
<langsyntaxhighlight lang=eC>void drawMandelbrot(Bitmap bmp, float range, Complex center, ColorAlpha * palette, int nPalEntries, int nIterations, float scale)
{
int x, y;
Line 3,759:
}
}
}</langsyntaxhighlight>
Interactive class with Rubberband Zoom:
<langsyntaxhighlight lang=eC>class Mandelbrot : Window
{
caption = $"Mandelbrot";
Line 3,895:
}
 
Mandelbrot mandelbrotForm {};</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
(lib 'math) ;; fractal function
(lib 'plot)
Line 3,910:
 
;; result here [http://www.echolalie.org/echolisp/help.html#fractal]
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang=elixir>defmodule Mandelbrot do
def set do
xsize = 59
Line 3,941:
end
 
Mandelbrot.set</langsyntaxhighlight>
 
{{out}}
Line 3,971:
=={{header|Emacs Lisp}}==
===Text mode===
<langsyntaxhighlight lang=lisp>; === Mandelbrot ============================================
 
(setq mandel-size (cons 76 34))
Line 4,012:
(insert(format "%s" (mandel-iter (mandel-pos x y))))))))
 
(mandel)</langsyntaxhighlight>
{{output}}
<pre>----------------------------------------------------------------------------
Line 4,051:
===Graphical version===
With a few modifications (mandel-size, mandel-iter, string-to-image, mandel-pic), the code above can also render the Mandelbrot fractal to an XPM image and display it directly in the buffer. (You might have to scroll up in Emacs after the function has run to see its output.)
<langsyntaxhighlight lang=lisp>; === Graphical Mandelbrot ============================================
 
(setq mandel-size (cons 320 300))
Line 4,104:
(insert-image (string-to-image all)))
 
(mandel-pic)</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 4,115:
[https://github.com/ghulette/mandelbrot-erlang Geoff Hulette's GitHub repository] provides two alternative implementations which are very interesting.
 
<langsyntaxhighlight lang=erlang>
-module(mandelbrot).
 
Line 4,166:
 
% **************************************************
</syntaxhighlight>
</lang>
 
Output:
Line 4,215:
 
=={{header|ERRE}}==
<langsyntaxhighlight lang=ERRE>
PROGRAM MANDELBROT
 
Line 4,252:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
Note: This is a PC version which uses EGA 16-color 320x200. Graphic commands are taken from
PC.LIB library.
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>open System.Drawing
open System.Windows.Forms
type Complex =
Line 4,316:
 
let f = new Mandel()
do Application.Run(f)</langsyntaxhighlight>
 
=== Alternate version, applicable to text and GUI ===
''' Basic generation code '''
<langsyntaxhighlight lang=fsharp>
let getMandelbrotValues width height maxIter ((xMin,xMax),(yMin,yMax)) =
let mandIter (cr:float,ci:float) =
Line 4,333:
fun y x -> mandIter ((xMin + dx * float(x)), (yMin + dy * float(y)))
[0..height-1] |> List.map(fun y->[0..width-1] |> List.map (forPos y))
</syntaxhighlight>
</lang>
 
''' Text display '''
<langsyntaxhighlight lang=fsharp>
getMandelbrotValues 80 25 50 ((-2.0,1.0),(-1.0,1.0))
|> List.map(fun row-> row |> List.map (function | 0 ->" " |_->".") |> String.concat "")
|> List.iter (printfn "%s")
</syntaxhighlight>
</lang>
 
Results:
Line 4,373:
 
''' Graphics display '''
<langsyntaxhighlight lang=fsharp>
open System.Drawing
open System.Windows.Forms
Line 4,394:
 
showGraphic toColor 640 480 5000 ((-2.0,1.0),(-1.0,1.0))
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
 
<langsyntaxhighlight lang=Factor>
! with ("::") or without (":") generalizations:
! : [a..b] ( steps a b -- a..b ) 2dup swap - 4 nrot 1 - / <range> ;
Line 4,431:
70 25 1000 mandel
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,466:
=={{header|Fennel}}==
 
<langsyntaxhighlight lang=Fennel>
#!/usr/bin/env fennel
 
Line 4,497:
max (arg-def 3 1e5)]
(mandel width height max))
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<langsyntaxhighlight lang=FOCAL>1.1 S I1=-1.2; S I2=1.2; S R1=-2; S R2=.5
1.2 S MIT=30
1.3 F Y=1,24; D 2
Line 4,524:
5.1 S T=MIT; T "*"; R
 
6.1 T " "; R</langsyntaxhighlight>
{{output}}
<pre>
Line 4,555:
=={{header|Forth}}==
This uses [[grayscale image]] utilities.
<langsyntaxhighlight lang=Forth>500 value max-iter
 
: mandel ( gmp F: imin imax rmin rmax -- )
Line 4,578:
 
80 24 graymap
dup -1e 1e -2e 1e mandel</langsyntaxhighlight>
{{works with|4tH v3.64}}
This is a completely integer version without local variables, which uses 4tH's native graphics library.
<langsyntaxhighlight lang=Forth>include lib/graphics.4th \ graphics support is needed
 
640 pic_width ! \ width of the image
Line 4,624:
s" mandelbt.ppm" save_image \ done, save the image
dup gshow
free bye</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{Works with|Fortran|90 and later}}
<langsyntaxhighlight lang=fortran>program mandelbrot
 
implicit none
Line 4,683:
close (10)
 
end program mandelbrot</langsyntaxhighlight>bs
=={{header|Frink}}==
This draws a graphical Mandelbrot set using Frink's built-in graphics and complex arithmetic.
<langsyntaxhighlight lang=Frink>
// Maximum levels for each pixel.
levels = 60
Line 4,722:
 
g.show[]
</syntaxhighlight>
</lang>
 
=={{header|Furor}}==
 
<langsyntaxhighlight lang=Furor>
###sysinclude X.uh
$ff0000 sto szin
Line 4,771:
{ „XRES” }
{ „myscreen” }
</syntaxhighlight>
</lang>
 
 
Line 4,778:
Computes escapes for each pixel, but not the colour.
 
<langsyntaxhighlight lang=Futhark>
default(f32)
 
Line 4,819:
fun main(screenX: int, screenY: int, depth: int, xmin: f32, ymin: f32, xmax: f32, ymax: f32): [screenX][screenY]int =
mandelbrot(screenX, screenY, depth, (xmin, ymin, xmax, ymax))
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang=futurebasic>
_xmin = -8601
_xmax = 2867
Line 4,866:
 
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 4,909:
=={{header|GLSL}}==
Uses smooth coloring.
<langsyntaxhighlight lang=glsl>
const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
Line 4,960:
}
 
</syntaxhighlight>
</lang>
 
=={{header|gnuplot}}==
The output from gnuplot is controlled by setting the appropriate values for the options <code>terminal</code> and <code>output</code>.
<langsyntaxhighlight lang=gnuplot>set terminal png
set output 'mandelbrot.png'</langsyntaxhighlight>
The following script draws an image of the number of iterations it takes to escape the circle with radius <code>rmax</code> with a maximum of <code>nmax</code>.
<langsyntaxhighlight lang=gnuplot>rmax = 2
nmax = 100
complex (x, y) = x * {1, 0} + y * {0, 1}
Line 4,975:
set pm3d map
set size square
splot [-2 : .8] [-1.4 : 1.4] mandelbrot (complex (0, 0), complex (x, y), 0) notitle</langsyntaxhighlight>
{{out}}
[[File:mandelbrot.png]]
Line 4,982:
;Text
Prints an 80-char by 41-line depiction.
<langsyntaxhighlight lang=go>package main
 
import "fmt"
Line 5,005:
fmt.Println("")
}
}</langsyntaxhighlight>
;Graphical
[[File:GoMandelbrot.png|thumb|right|.png image]]
<langsyntaxhighlight lang=go>package main
 
import (
Line 5,067:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
 
=={{header|Golfscript}}==
Código sacado de https://codegolf.stackexchange.com/
<langsyntaxhighlight lang=golfscript>20{40{0.1{.{;..*2$.*\-
20/3$-@@*10/3$-..*2$.*+1600<}*}32*'
*'=\;\;@@(}60*;(n\}40*;]''+</langsyntaxhighlight>
{{out}}
<pre>000000000000000000000000000000000000000010000000000000000000
Line 5,119:
=={{header|Hare}}==
{{trans|D}}
<langsyntaxhighlight lang=hare>use fmt;
use math;
 
Line 5,148:
fn abs(z: complex) f64 = {
return math::sqrtf64(z.re*z.re + z.im*z.im);
};</langsyntaxhighlight>
{{out}}
<pre>
Line 5,203:
=={{header|Haskell}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=haskell>import Data.Bool ( bool )
import Data.Complex (Complex ((:+)), magnitude)
 
Line 5,217:
]
| y <- [1, 0.95 .. -1]
]</langsyntaxhighlight>
{{Out}}
<pre>
Line 5,257:
 
'''haskell one-liners :'''
<langsyntaxhighlight lang=haskell>
 
-- first attempt
Line 5,272:
 
-- open GHCI > Copy and paste any of above one-liners > Hit enter
</syntaxhighlight>
</lang>
 
A legible variant of the first of the "one-liner" contributions above:
 
<langsyntaxhighlight lang=haskell>main :: IO ()
main =
putStrLn $
Line 5,307:
)
[".", "\'", ":", "!", "|", "}", "#", " "]
)</langsyntaxhighlight>
{{Out}}
<pre> #
Line 5,400:
 
and a legible variant of the last of the "one-liner" contributions above:
<langsyntaxhighlight lang=haskell>main :: IO ()
main =
mapM_
Line 5,419:
else ' '
]
]</langsyntaxhighlight>
 
=={{header|Haxe}}==
This version compiles for flash version 9 or greater.
The compilation command is
<langsyntaxhighlight lang=haxe>haxe -swf mandelbrot.swf -main Mandelbrot</langsyntaxhighlight>
 
<langsyntaxhighlight lang=haxe>class Mandelbrot extends flash.display.Sprite
{
inline static var MAX_ITER = 255;
Line 5,474:
image.setPixel(x, y, color);
}
}</langsyntaxhighlight>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang=huginn>#! /bin/sh
exec huginn -E "${0}" "${@}"
#! huginn
Line 5,531:
columns -= 1;
return ( ( lines, columns ) );
}</langsyntaxhighlight>
 
{{out}}
Line 5,580:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang=Icon>link graphics
 
procedure main()
Line 5,625:
procedure cAbs(x)
return sqrt(x.r*x.r+x.i*x.i)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 5,636:
(free implementation: GDL - GNU Data Language
http://gnudatalanguage.sourceforge.net)
<langsyntaxhighlight lang=IDL>
PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations
 
Line 5,683:
END
 
</syntaxhighlight>
</lang>
from the command line:
<langsyntaxhighlight lang=IDL>
GDL>.run mandelbrot
</syntaxhighlight>
</lang>
or
<langsyntaxhighlight lang=IDL>
GDL> Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200
</syntaxhighlight>
</lang>
 
=={{header|Inform 7}}==
{{libheader|Glimmr Drawing Commands by Erik Temple}}
{{works with|Glulx virtual machine}}
<langsyntaxhighlight lang=inform7>"Mandelbrot"
 
The story headline is "A Non-Interactive Set".
Line 5,881:
[ fneg n; @bitxor n $80000000 n; return n; ];
#endif;
-).</langsyntaxhighlight>
 
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.
Line 5,889:
=={{header|J}}==
The characteristic function of the Mandelbrot can be defined as follows:
<langsyntaxhighlight lang=j>mcf=. (<: 2:)@|@(] ((*:@] + [)^:((<: 2:)@|@])^:1000) 0:) NB. 1000 iterations test</langsyntaxhighlight>
The Mandelbrot set can be drawn as follows:
<langsyntaxhighlight lang=j>domain=. |.@|:@({.@[ + ] *~ j./&i.&>/@+.@(1j1 + ] %~ -~/@[))&>/
 
load 'viewmat'
viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.01 NB. Complex interval and resolution</langsyntaxhighlight>
 
A smaller version, based on a black&white implementation of viewmat (and paraphrased, from html markup to wiki markup), is shown [[Mandelbrot_set/J/Output|here]] (The output is HTML-heavy and was split out to make editing this page easier):
 
<langsyntaxhighlight lang=j> viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.1 NB. Complex interval and resolution</langsyntaxhighlight>
 
=={{header|Java}}==
{{libheader|Swing}} {{libheader|AWT}}
<langsyntaxhighlight lang=java>import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
Line 5,944:
new Mandelbrot().setVisible(true);
}
}</langsyntaxhighlight>
=== Interactive ===
{{libheader|AWT}} {{libheader|Swing}}
<langsyntaxhighlight lang=java>import static java.awt.Color.HSBtoRGB;
import static java.awt.Color.black;
import static java.awt.event.KeyEvent.VK_BACK_SLASH;
Line 6,240:
;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 6,249:
The code can be run directly from the Javascript console in modern browsers by copying and pasting it.
 
<langsyntaxhighlight lang=javascript>function mandelIter(cx, cy, maxIter) {
var x = 0.0;
var y = 0.0;
Line 6,317:
document.body.insertBefore(canvas, document.body.childNodes[0]);
 
mandelbrot(canvas, -2, 1, -1, 1, 1000);</langsyntaxhighlight>
 
{{out}} with default parameters:
Line 6,327:
one for instance with the [https://mbebenita.github.io/WasmExplorer/ WebAssembly explorer]
 
<langsyntaxhighlight lang=javascript>var mandelIter;
fetch("./mandelIter.wasm")
.then(res => {
Line 6,348:
mandelbrot(canvas, -2, 1, -1, 1, 1000);
// ...
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 6,358:
 
'''Preliminaries'''
<langsyntaxhighlight lang=jq># SVG STUFF
def svg(id; width; height):
"<svg width='\(width // "100%")' height='\(height // "100%") '
Line 6,372:
def u: if condition then . else (next|u) end;
u;
</langsyntaxhighlight><syntaxhighlight lang =jq>
def Mandeliter( cx; cy; maxiter ):
# [i, x, y, x^2+y^2]
Line 6,412:
svg("mandelbrot"; "100%"; "100%"),
pixies,
"</svg>";</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang=jq> Mandelbrot( {"xmin": -2, "xmax": 1, "ymin": -1, "ymax":1}; 900; 600; 1000 ) </langsyntaxhighlight>
 
'''Execution:'''
Line 6,426:
 
Generates an ASCII representation:
<langsyntaxhighlight lang=python>function mandelbrot(a)
z = 0
for i=1:50
Line 6,439:
end
println()
end</langsyntaxhighlight>
 
This generates a PNG image file:
<langsyntaxhighlight lang=python>using Images
 
@inline function hsv2rgb(h, s, v)
Line 6,481:
 
img = mandelbrot()
save("mandelbrot.png", img)</langsyntaxhighlight>
 
===Mandelbrot Set with Julia Animation===
This is an extension of the corresponding R section: e^(-|z|)-smoothing was added.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, legend=false, axis=false, ticks=false, dpi=100)
 
Line 6,511:
 
gif(animation, "Mandelbrot_animation.gif", fps=2)
gif(smoothing, "Mandelbrot_smoothing.gif", fps=2)</langsyntaxhighlight>
 
===Normalized Counting, Distance Estimation, Mercator Maps and Perturbation Theory ===
This is an extension of the corresponding Python section to include higher precision calculations for larger zoom depths. The ''e^(-|z|)-smoothing'', ''normalized iteration count'' and ''exterior distance estimation'' algorithms are used.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
 
Line 6,549:
 
heatmap(D .^ 0.1, c=:jet)
savefig("Mandelbrot_set_3.png")</langsyntaxhighlight>
 
A small change in the code above creates Mercator maps and zoom images of the Mandelbrot set. The abs2 function is used to speed up the calculations inside the loop. See also the album [https://www.flickr.com/photos/arenamontanus/albums/72157615740829949 Mercator Mandelbrot Maps] by Anders Sandberg.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
 
Line 6,587:
p4 = scatter(X[4*z+1:4*z+c,:], Y[4*z+1:4*z+c,:], markersize=R[1:c,:], marker_z=D[4*z+1:4*z+c,:].^0.2, c=:nipy_spectral)
plot(p1, p2, p3, p4, layout=(2, 2))
savefig("Mercator_Mandelbrot_plot.png")</langsyntaxhighlight>
 
For deep zoom images it is sufficient to calculate a single point with high accuracy. A good approximation can then be found for all other points by means of a perturbation calculation with standard accuracy. Placing the iteration in a separate function speeds up the calculation. See [https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set#Perturbation_theory_and_series_approximation Perturbation theory] (Wikipedia) and [https://gbillotey.github.io/Fractalshades-doc/math.html Mathematical background] (Fractalshades) for more details.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
 
Line 6,636:
 
heatmap(D .^ 0.25, c=:nipy_spectral)
savefig("Mandelbrot_deep_zoom.png")</langsyntaxhighlight>
 
Of course, deep Mercator maps can also be created. See also the image [https://www.flickr.com/photos/arenamontanus/3430921497/in/album-72157615740829949/ Deeper Mercator Mandelbrot] by Anders Sandberg. To reduce glitches, an additional reference sequence for the derivation (dS) is recorded with high precision.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
 
Line 6,685:
 
heatmap(D' .^ 0.025, c=:nipy_spectral)
savefig("Mercator_Mandelbrot_deep_map.png")</langsyntaxhighlight>
 
Due to abs(z - epsilon) < 2 and the second reference sequence, Z and dZ can be calculated after the loop. This massively reduces the computing time.
<langsyntaxhighlight lang=julia>Z, dZ, E, dE = zero(C), zero(C), zero(C), zero(C)
D, I = zeros(size(C)), ones(Int64, size(C))
 
Line 6,701:
 
N = abs.(Z) .> 2 # exterior distance estimation
D[N] = 0.5 .* log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N])</langsyntaxhighlight>
 
Another approach to reducing glitches is rebasing. See [https://gbillotey.github.io/Fractalshades-doc/math.html#avoiding-loss-of-precision Avoiding loss of precision] (Fractalshades) and [https://fractalforums.org/fractal-mathematics-and-new-theories/28/another-solution-to-perturbation-glitches/4360 Another solution to perturbation glitches] (Fractalforums) for details.
<langsyntaxhighlight lang=julia>Z, dZ, E = zero(C), zero(C), zero(C)
D, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C))
 
Line 6,718:
 
N = abs.(Z) .> 2 # exterior distance estimation
D[N] = 0.5 .* log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N])</langsyntaxhighlight>
 
The rebasing condition abs(z) < abs(epsilon) does not define a circular area but a half-plane. If you insert a factor, the condition abs(z) < gamma * abs(epsilon) for 0 < gamma < 1 defines a circular area containing the origin. For example, if the reference point is at S(1, 0), the equation abs(z) = abs(epsilon) defines the set of all points that are equidistant from O(0, 0) and S(1, 0). This is exactly the perpendicular bisector x = 1/2. Considering instead the equation abs(z) = 1/2 * abs(epsilon), one finds all points half as far from O(0, 0) as from S(1, 0). All these points lie on a circle, which has center M(-1/3, 0) and radius R = 2/3. If you choose a factor gamma > 1, you get corresponding circles containing the reference point S. However, the condition abs(z) < abs(epsilon) is optimal because it keeps the differences epsilon to the reference sequence as small as possible. Rebasing occurs if and only if the distance abs(epsilon) to the reference sequence becomes smaller as a result. You can only rebase to the beginning of the reference sequence. If you want to rebase to the reference point S[m], the difference epsilon = z - S[m] must be calculated. With this subtraction, however, the entire precision is lost due to cancellation. Only at the first reference point there is no cancellation due to S[1] = 0, because epsilon = z - S[1] = z - 0 = z. The images can be verified by a (slow) calculation with BigFloats.
<langsyntaxhighlight lang=julia>using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
 
Line 6,753:
 
heatmap(D' .^ 0.025, c=:nipy_spectral)
savefig("Mercator_Mandelbrot_big_map.png")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>// version 1.1.2
 
import java.awt.Graphics
Line 6,801:
fun main(args: Array<String>) {
Mandelbrot().isVisible = true
}</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
Line 6,809:
 
=={{header|Lang5}}==
<langsyntaxhighlight lang=Lang5>
: d2c(*,*) 2 compress 'c dress ; # Make a complex number.
 
Line 6,823:
 
iterate abs int 5 min 'print_line apply # Compute & print
</syntaxhighlight>
</lang>
 
=={{header|Lambdatalk}}==
Line 6,832:
Here we show a pure lambdatalk code, a slow but minimalistic and easy to understand version without the burden of any canvas. We just compute if a point is inside or outside the mandelbrot set and just write "o" or "." directly in the wiki page.
 
<langsyntaxhighlight lang=Scheme>
{def mandel
 
Line 6,864:
{S.serie 0 40}} // y resolution
 
</syntaxhighlight>
</lang>
 
<pre>
Line 6,911:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=Lasso>
define mandelbrotBailout => 16
define mandelbrotMaxIterations => 1000
Line 6,963:
 
mandelbrotTest
</syntaxhighlight>
</lang>
{{out}}
<small>
Line 7,048:
=={{header|LIL}}==
From the source distribution. Produces a PBM, not shown here.
<langsyntaxhighlight lang=tcl>#
# A mandelbrot generator that outputs a PBM file. This can be used to measure
# performance differences between LIL versions and measure performance
Line 7,109:
}}
}
}</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang=logo>to mandelbrot :left :bottom :side :size
cs setpensize [1 1]
make "inc :side/:size
Line 7,147:
end
 
mandelbrot -2 -1.25 2.5 400</langsyntaxhighlight>
 
=={{header|Lua}}==
===Graphical===
Needs L&Ouml;VE 2D Engine<br />Zoom in: drag the mouse; zoom out: right click
<langsyntaxhighlight lang=lua>
local maxIterations = 250
local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5
Line 7,221:
love.graphics.draw( canvas )
end
</syntaxhighlight>
</lang>
===ASCII===
<langsyntaxhighlight lang=lua>-- Mandelbrot set in Lua 6/15/2020 db
local charmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "@" }
for y = -1.3, 1.3, 0.1 do
Line 7,235:
end
print()
end</langsyntaxhighlight>
{{out}}
<pre>...............::::::::::::::::::---------------::::::::::::::::::::::::::::::::
Line 7,268:
Console is a bitmap so we can plot on it. A subroutine plot different size of pixels so we get Mandelbrot image at final same size for 32X26 for a big pixel of 16x16 pixels to 512x416 for a 1:1 pixel. Iterations for each pixel set to 25. Module can get left top corner as twips, and the size factor from 1 to 16 (size of output is 512x416 pixels for any factor).
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
Line 7,308:
}
 
</syntaxhighlight>
</lang>
 
Version 2 without Subroutine. Also there is a screen refresh every 2 seconds.
<langsyntaxhighlight lang=M2000 Interpreter>
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
Line 7,350:
Mandelbrot 250*twipsx,100*twipsy, array(i)
}
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<lang>ImageTools:-Embed(Fractals[EscapeTime]:-Mandelbrot(500, -2.0-1.35*I, .7+1.35*I, output = layer1));</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The implementation could be better. But this is a start...
<langsyntaxhighlight lang=mathematica>eTime[c_, maxIter_Integer: 100] := Length@NestWhileList[#^2 + c &, 0, Abs@# <= 2 &, 1, maxIter] - 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]</langsyntaxhighlight>
Faster version:
<langsyntaxhighlight lang=mathematica>cf = With[{
mandel = Block[{z = #, c = #},
Catch@Do[If[Abs[z] > 2, Throw@i]; z = z^2 + c, {i, 100}]] &
Line 7,369:
Compile[{},Table[mandel[y + x I], {x, -1, 1, 0.005}, {y, -2, 0.5, 0.005}]]
];
ArrayPlot[cf[]] </langsyntaxhighlight>
Built-in function:
<syntaxhighlight lang =mathematica>MandelbrotSetPlot[]</langsyntaxhighlight>
 
==Mathmap ==
Line 7,392:
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.
 
<langsyntaxhighlight lang=MATLAB>function [theSet,realAxis,imaginaryAxis] = mandelbrotSet(start,gridSpacing,last,maxIteration)
 
%Define the escape time algorithm
Line 7,424:
shading flat;
end</langsyntaxhighlight>
 
To use this function you must specify the:
Line 7,443:
 
Sample usage:
<langsyntaxhighlight lang=MATLAB>mandelbrotSet(-2.05-1.2i,0.004+0.0004i,0.45+1.2i,500);</langsyntaxhighlight>
 
=={{header|Metapost}}==
<langsyntaxhighlight lang=Metapost>prologues:=3;
outputtemplate:="%j-%c.svg";
outputformat:="svg";
Line 7,489:
endfig;
 
end</langsyntaxhighlight>
 
Sample usage:
<langsyntaxhighlight lang=Bash>mpost -numbersystem="double" mandelbrot.mp</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight lang=MiniScript>ZOOM = 100
MAX_ITER = 40
gfx.clear color.black
Line 7,514:
end if
end for
end for</langsyntaxhighlight>
 
(Will upload an output image as soon as image uploading is fixed.)
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang=modula3>MODULE Mandelbrot EXPORTS Main;
 
IMPORT Wr, Stdio, Fmt, Word;
Line 7,574:
END;
END;
END Mandelbrot.</langsyntaxhighlight>
 
=={{header|MySQL}}==
Line 7,580:
See http://arbitraryscrawl.blogspot.co.uk/2012/06/fractsql.html for an explanation.
 
<langsyntaxhighlight lang=mysql>
-- Table to contain all the data points
CREATE TABLE points (
Line 7,677:
INTO OUTFILE '/tmp/image.ppm'
FROM points;
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Line 7,685:
{{trans|Python}}
 
<langsyntaxhighlight lang=nim>import complex
 
proc inMandelbrotSet(c: Complex, maxEscapeIterations = 50): bool =
Line 7,704:
result.add('\n')
 
echo mandelbrotImage(1.0, -0.05, -2.0, 0.0315, 40, 80)</langsyntaxhighlight>
 
{{out}}
Line 7,748:
{{trans|Julia}}
{{libheader|imageman}}
<langsyntaxhighlight lang=Nim>import math, complex, lenientops
import imageman
 
Line 7,784:
img[x - 1, y - 1] = ColorRGBF64(color)
 
img.savePNG("mandelbrot.png", compression = 9)</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang=ocaml>#load "graphics.cma";;
 
let mandelbrot xMin xMax yMin yMax xPixels yPixels maxIter =
Line 7,814:
done;;
mandelbrot (-1.5) 0.5 (-1.0) 1.0 500 500 200;;</langsyntaxhighlight>
 
=={{header|Octave}}==
Line 7,820:
This code runs rather slowly and produces coloured Mandelbrot set by accident ([[Media:Mandel-Octave.jpg|output image]]).
 
<langsyntaxhighlight lang=octave>#! /usr/bin/octave -qf
global width = 200;
global height = 200;
Line 7,853:
endfor
 
saveimage("mandel.ppm", round(ms .* 255).', "ppm");</langsyntaxhighlight>
 
A bit faster than the above implementation
 
<langsyntaxhighlight lang=octave>
function z = mandelbrot()
% to view the image call "image(mandelbrot())"
Line 7,879:
z = abs(z);
end
</syntaxhighlight>
</lang>
 
=={{header|Ol}}==
<langsyntaxhighlight lang=scheme>
(define x-size 59)
(define y-size 21)
Line 7,912:
(print)))
(iota y-size))
</syntaxhighlight>
</lang>
 
Output:
Line 7,940:
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang=Progress (OpenEdge ABL)>DEFINE VARIABLE print_str AS CHAR NO-UNDO INIT ''.
DEFINE VARIABLE X1 AS DECIMAL NO-UNDO INIT 50.
DEFINE VARIABLE Y1 AS DECIMAL NO-UNDO INIT 21.
Line 7,984:
MESSAGE print_str.
OUTPUT CLOSE.
</langsyntaxhighlight>Example :<BR>
 
=={{header|PARI/GP}}==
Define function mandelbrot():
<langsyntaxhighlight lang=parigp>mandelbrot() =
{
forstep(y=-1, 1, 0.05,
Line 7,994:
print1(((c)->my(z=c);for(i=1,20,z=z*z+c;if(abs(z)>2,return(" ")));"#")(x+y*I)));
print());
}</langsyntaxhighlight>
 
Output:<pre>gp > mandelbrot()
Line 8,041:
=={{header|Pascal}}==
{{trans|C}}
<langsyntaxhighlight lang=pascal>program mandelbrot;
{$IFDEF FPC}
Line 8,136:
close(outfile);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
translation / optimization of the ruby solution
<langsyntaxhighlight lang=perl>use Math::Complex;
 
sub mandelbrot {
Line 8,154:
{print mandelbrot($x + $y * i) ? ' ' : '#'}
print "\n"
}</langsyntaxhighlight>
 
=={{header|Phix}}==
;Ascii
This is included in the distribution (with some extra validation) as demo\mandle.exw
<langsyntaxhighlight lang=Phix>--
-- Mandlebrot set in ascii art demo.
--
Line 8,183:
puts(1,b[remainder(k,16)+1])
end for
end for</langsyntaxhighlight>
;Graphical
This is included in the distribution as demo\arwendemo\mandel.exw
<langsyntaxhighlight lang=Phix>include arwen.ew
include ..\arwen\dib256.ew
 
Line 8,426:
 
WinMain(Main,SW_NORMAL)
void = deleteDib(0)</langsyntaxhighlight>
 
=={{header|PHP}}==
Line 8,434:
[[File:Mandel-php.png|thumb|right|Sample output]]
 
<langsyntaxhighlight lang=PHP>$min_x=-2;
$max_x=1;
$min_y=-1;
Line 8,473:
imagepng($im);
imagedestroy($im);
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
{{trans|Unicon}}
Picat has not support for fancy graphics so it's plain 0/1 ASCII. Also, there's no built-in support for complex numbers.
<langsyntaxhighlight lang=Picat>go =>
 
Width = 90,
Line 8,507:
c_add(X,Y) = complex(X[1]+Y[1],X[2]+Y[2]).
c_mul(X,Y) = complex(X[1]*Y[1]-X[2]*Y[2],X[1]*Y[2]+X[2]*Y[1]).
c_abs(X) = sqrt(X[1]*X[1]+X[2]*X[2]).</langsyntaxhighlight>
 
{{out}}
Line 8,562:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(scl 6)
 
(let Ppm (make (do 300 (link (need 400))))
Line 8,579:
(prinl 400 " " 300)
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) )</langsyntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight lang=postscript>%!PS-Adobe-2.0
%%BoundingBox: 0 0 300 200
%%EndComments
Line 8,627:
showpage
origstate restore
%%EOF</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang=PowerShell>
$x = $y = $i = $j = $r = -16
$colors = [Enum]::GetValues([System.ConsoleColor])
Line 8,651:
Write-Host
}
</syntaxhighlight>
</lang>
 
=={{header|Processing}}==
Click on an area to zoom in. Choose areas with multiple colors for interesting zooming.
<langsyntaxhighlight lang=java>double x, y, zr, zi, zr2, zi2, cr, ci, n;
double zmx1, zmx2, zmy1, zmy2, f, di, dj;
double fn1, fn2, fn3, re, gr, bl, xt, yt, i, j;
Line 8,714:
i = 0;
j = 0;
}</langsyntaxhighlight>'''The sketch can be run online''' :<BR> [https://www.openprocessing.org/sketch/794150 here.]
 
==={{header|Processing Python mode}}===
Click on an area to zoom in.
Choose areas with multiple colors for interesting zooming.
<langsyntaxhighlight lang=python>i = di = dj = 0
fn1, fn2, fn3 = random(20), random(20), random(20)
f = 10
Line 8,769:
zmy2 = zmy2 * (1. / f)
di, dj = di * f, dj * f
i = j = 0</langsyntaxhighlight>
 
=={{header|Prolog}}==
SWI-Prolog has a graphic interface XPCE :
<langsyntaxhighlight lang=Prolog>:- use_module(library(pce)).
 
mandelbrot :-
Line 8,811:
compute_RGB(CX, CY, Tmp, ZY1, Iter1, IterF).
 
compute_RGB(_CX, _CY, _ZX, _ZY, Iter, Iter).</langsyntaxhighlight>Example :<BR>
[[FILE:Mandelbrot.jpg]]
 
Line 8,818:
=={{header|Python}}==
Translation of the ruby solution
<langsyntaxhighlight lang=python># Python 3.0+ and 2.5+
try:
from functools import reduce
Line 8,836:
 
print("\n".join("".join(row) for row in rows))
</syntaxhighlight>
</lang>
 
A more "Pythonic" version of the code:
<langsyntaxhighlight lang=python>
import math
 
Line 8,854:
for y in [a * 0.05 for a in range(-20, 20)]])
)
</syntaxhighlight>
</lang>
 
Finally, we can also use Matplotlib to visualize the Mandelbrot set with Python:
{{libheader|matplotlib}}
{{libheader|NumPy}}
<langsyntaxhighlight lang=python>from pylab import *
from numpy import NaN
 
Line 8,883:
ylabel("Im(c)")
savefig("mandelbrot_python.svg")
show()</langsyntaxhighlight>
 
Another Numpy version using masks to avoid (explicit) nested loops.
Runs about 16x faster for the same resolution.
<langsyntaxhighlight lang=python>import matplotlib.pyplot as plt
import numpy as np
 
Line 8,913:
cmap=plt.cm.prism,
extent=(X.min(), X.max(), Y.min(), Y.max()))
plt.show()</langsyntaxhighlight>
 
===Normalized Counting, Distance Estimation, Mercator Maps and Deep Zoom===
The Mandelbrot set is printed with smooth colors.
The ''e^(-|z|)-smoothing'', ''normalized iteration count'' and ''exterior distance estimation'' algorithms are used with NumPy and complex matrices (see Javier Barrallo & Damien M. Jones: [http://www.mi.sanu.ac.rs/vismath/javier/index.html ''Coloring Algorithms for Dynamical Systems in the Complex Plane''] and Mikael Hvidtfeldt Christensen: [http://blog.hvidtfeldts.net/index.php/2011/09/distance-estimated-3d-fractals-v-the-mandelbulb-different-de-approximations ''Distance Estimated 3D Fractals (V): The Mandelbulb & Different DE Approximations'']).
<langsyntaxhighlight lang=python>import numpy as np
import matplotlib.pyplot as plt
 
Line 8,951:
 
plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted)
plt.savefig("Mandelbrot_set_3.png", dpi=200)</langsyntaxhighlight>
 
A small change in the code above creates Mercator maps of the Mandelbrot set (see David Madore: [http://www.madore.org/~david/math/mandelbrot.html ''Mandelbrot set images and videos''] and Anders Sandberg: [https://www.flickr.com/photos/arenamontanus/sets/72157615740829949 ''Mercator Mandelbrot Maps'']).
Line 8,959:
With the same pixel density and the same maximum magnification, the difference in height between the maps is only about 10 percent.
By misusing a scatter plot, it is possible to create zoom images of the Mandelbrot set.
<langsyntaxhighlight lang=python>import numpy as np
import matplotlib.pyplot as plt
 
Line 8,992:
ax[1, 0].scatter(X[3*z:3*z+c], Y[3*z:3*z+c], s=R[0:c]**2, c=D[3*z:3*z+c]**0.3, cmap=plt.cm.nipy_spectral)
ax[1, 1].scatter(X[4*z:4*z+c], Y[4*z:4*z+c], s=R[0:c]**2, c=D[4*z:4*z+c]**0.2, cmap=plt.cm.nipy_spectral)
plt.savefig("Mercator_Mandelbrot_plot.png", dpi=100)</langsyntaxhighlight>
 
For deep zoom images it is sufficient to calculate a single point with high accuracy. A good approximation can then be found for all other points by means of a perturbation calculation with standard accuracy. See [https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set#Perturbation_theory_and_series_approximation Perturbation theory] (Wikipedia) and [https://gbillotey.github.io/Fractalshades-doc/math.html Mathematical background] (Fractalshades) for more details. Placing the iteration in a separate function speeds up the calculation slightly.
<langsyntaxhighlight lang=python>import numpy as np
import matplotlib.pyplot as plt
 
Line 9,038:
 
plt.imshow(D ** 0.25, cmap=plt.cm.nipy_spectral)
plt.savefig("Mandelbrot_deep_zoom.png", dpi=200)</langsyntaxhighlight>
 
Of course, deep Mercator maps can also be created. See also the image [https://www.flickr.com/photos/arenamontanus/3430921497/in/album-72157615740829949/ Deeper Mercator Mandelbrot] by Anders Sandberg. To reduce glitches, an additional reference sequence for the derivation (dS) is recorded with high precision. Compare the corresponding program examples for the Julia language for more details.
<langsyntaxhighlight lang=python>import numpy as np
import matplotlib.pyplot as plt
 
Line 9,084:
 
plt.imshow(D.T ** 0.025, cmap=plt.cm.nipy_spectral)
plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200)</langsyntaxhighlight>
 
===Python - "One liner"===
<langsyntaxhighlight lang=python>
print(
'\n'.join(
Line 9,096:
for y in range(-50,50)
))
</syntaxhighlight>
</lang>
 
=={{header|R}}==
<langsyntaxhighlight lang=R>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.
Line 9,121:
function(z,c)z^2+c, function(z)abs(z) <= 2,
max=100)
image(x)</langsyntaxhighlight>
 
===Mandelbrot Set with R Animation===
Modified Mandelbrot set animation by Jarek Tuszynski, PhD. (see: [https://en.wikipedia.org/wiki/R_(programming_language)#Mandelbrot_set Wikipedia: R (programming_language)] and [https://rtricks.blogspot.com/2007/04/mandelbrot-set-with-r-animation.html R Tricks: Mandelbrot Set with R Animation])
<langsyntaxhighlight lang=R>#install.packages("caTools") # install external package (if missing)
library(caTools) # external package providing write.gif function
jet.colors <- colorRampPalette(c("red", "blue", "#007FFF", "cyan", "#7FFF7F",
Line 9,140:
X[, , k] <- exp(-abs(Z)) # capture results
}
write.gif(X, "Mandelbrot.gif", col = jet.colors, delay = 100)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>
#lang racket
 
Line 9,170:
 
(mandelbrot 300 200)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 9,180:
Converted to a .png file for display here.
 
<langsyntaxhighlight lang=perl6>constant @color_map = map ~*.comb(/../).map({:16($_)}), <
000000 0000fc 4000fc 7c00fc bc00fc fc00fc fc00bc fc007c fc0040 fc0000 fc4000
fc7c00 fcbc00 fcfc00 bcfc00 7cfc00 40fc00 00fc00 00fc40 00fc7c 00fcbc 00fcfc
Line 9,228:
put @color_map[|.reverse, |.[1..*]][^$width] given
my @ = map &mandelbrot.assuming(0i, *), $re «+« @im;
}</langsyntaxhighlight>
 
Alternately, a more modern, faster version.
 
<langsyntaxhighlight lang=perl6>use Image::PNG::Portable;
 
my ($w, $h) = 800, 800;
Line 9,279:
} ).map: ((*+$m) * 255).Int]
}
}</langsyntaxhighlight>
See [https://github.com/thundergnat/rc/blob/master/img/Mandelbrot-set-perl6.png Mandelbrot-set-perl6.png] (offsite .png image)
 
Line 9,286:
{{trans|AWK}}
This REXX version doesn't depend on the ASCII sequence of glyphs; &nbsp; an internal character string was used that mimics a part of the ASCII glyph sequence.
<langsyntaxhighlight lang=rexx>/*REXX program generates and displays a Mandelbrot set as an ASCII art character image.*/
@ = '>=<;:9876543210/.-,+*)(''&%$#"!' /*the characters used in the display. */
Xsize = 59; minRE = -2; maxRE = +1; stepX = (maxRE-minRE) / Xsize
Line 9,302:
end /*x*/
say $ /*display a line of character output.*/
end /*y*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; using the internal defaults:
<pre>
Line 9,330:
===version 2===
This REXX version uses glyphs that are "darker" (with a white background) around the output's peripheral.
<langsyntaxhighlight lang=rexx>/*REXX program generates and displays a Mandelbrot set as an ASCII art character image.*/
@ = '█▓▒░@9876543210=.-,+*)(·&%$#"!' /*the characters used in the display. */
Xsize = 59; minRE = -2; maxRE = +1; stepX = (maxRE-minRE) / Xsize
Line 9,346:
end /*x*/
say $ /*display a line of character output.*/
end /*y*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; using the internal defaults:
<pre>
Line 9,374:
===version 3===
This REXX version produces a larger output &nbsp; (it uses the full width of the terminal screen (less one), &nbsp; and the height is one-half of the width.
<langsyntaxhighlight lang=rexx>/*REXX program generates and displays a Mandelbrot set as an ASCII art character image.*/
@ = '█▓▒░@9876543210=.-,+*)(·&%$#"!' /*the characters used in the display. */
parse arg Xsize Ysize . /*obtain optional arguments from the CL*/
Line 9,393:
end /*x*/
say $ /*display a line of character output.*/
end /*y*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; using the internal defaults:
<pre>
Line 9,445:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
load "guilib.ring"
 
Line 9,499:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 9,507:
=={{header|Ruby}}==
Text only, prints an 80-char by 41-line depiction. Found [http://www.xcombinator.com/2008/02/22/ruby-inject-and-the-mandelbrot-set/ here].
<langsyntaxhighlight lang=ruby>require 'complex'
 
def mandelbrot(a)
Line 9,518:
end
puts
end</langsyntaxhighlight>
 
{{trans|Tcl}}
 
Uses [[Raster graphics operations/Ruby]]
<langsyntaxhighlight lang=ruby># frozen_string_literal: true
 
require_relative 'raster_graphics'
Line 9,560:
end
 
Pixmap.mandelbrot(300,300).save('mandel.ppm')</langsyntaxhighlight>
 
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby
<langsyntaxhighlight lang=ruby>
# frozen_string_literal: true
 
Line 9,603:
size(900, 600)
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Dependencies: image, num-complex
<langsyntaxhighlight lang=rust>extern crate image;
extern crate num_complex;
 
Line 9,647:
// Save image
imgbuf.save("fractal.png").unwrap();
}</langsyntaxhighlight>
 
=={{header|Sass/SCSS}}==
<langsyntaxhighlight lang=coffeescript>
$canvasWidth: 200;
$canvasHeight: 200;
Line 9,697:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
Line 9,703:
Uses RgbBitmap from [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] task and Complex number class from [[Arithmetic/Complex#Scala|this]]
programming task.
<langsyntaxhighlight lang=scala>import org.rosettacode.ArithmeticComplex._
import java.awt.Color
 
Line 9,745:
else new Color(255, 255, (255*(c-2)).toInt)
}
}</langsyntaxhighlight>
Read–eval–print loop
<langsyntaxhighlight lang=scala>import scala.swing._
import javax.swing.ImageIcon
val imgMandel=Mandelbrot.generate()
val mainframe=new MainFrame(){title="Test"; visible=true
contents=new Label(){icon=new ImageIcon(imgMandel.image)}
}</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang=scheme>(define x-centre -0.5)
(define y-centre 0.0)
(define width 4.0)
Line 9,796:
(begin (display (pixel i j)) (newline))))))))
 
(plot)</langsyntaxhighlight>
 
=={{header|Scratch}}==
Line 9,873:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang=sensetalk>put 0 into oReal # Real origin
put 0 into oImag # Imaginary origin
put 0.5 into mag # Magnification
Line 9,935:
 
close file myFile
</syntaxhighlight>
</lang>
 
=={{header|SequenceL}}==
'''SequenceL Code for Computing and Coloring:'''<br>
<langsyntaxhighlight lang=sequencel>import <Utilities/Complex.sl>;
import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;
Line 10,026:
linearInterpolate(v0(0), v1(0), t(0)) := (1 - t) * v0 + t * v1;
 
//endregion</langsyntaxhighlight>
 
'''C++ Driver Code:'''<br>
{{libheader|CImg}}
<langsyntaxhighlight lang=c>#include "SL_Generated.h"
#include "../../../ThirdParty/CImg/CImg.h"
 
Line 10,132:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 10,138:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>func mandelbrot(z) {
var c = z
{ z = (z*z + c)
Line 10,151:
}
print "\n"
}</langsyntaxhighlight>
 
 
=={{header|Simula}}==
{{trans|Scheme}}
<langsyntaxhighlight lang=simula>BEGIN
REAL XCENTRE, YCENTRE, WIDTH, RMAX, XOFFSET, YOFFSET, PIXELSIZE;
INTEGER N, IMAX, JMAX, COLOURMAX;
Line 10,240:
 
PLOT;
END;</langsyntaxhighlight>
 
=={{header|Spin}}==
Line 10,247:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<langsyntaxhighlight lang=spin>con
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 10,290:
 
waitcnt(_clkfreq+cnt)
ser.stop</langsyntaxhighlight>
 
{{out}}
Line 10,322:
 
=={{header|SPL}}==
<langsyntaxhighlight lang=spl>w,h = #.scrsize()
sfx = -2.5; sfy = -2*h/w; fs = 4/w
#.aaoff()
Line 10,339:
? n=maxn, <= 0,0,0
<= #.hsv2rgb(n/maxn*360,1,1):3
.</langsyntaxhighlight>
 
 
Line 10,346:
Using the Swift Numerics package, as well as the C library Quick 'N Dirty BMP imported in Swift.
 
<langsyntaxhighlight lang=swift>import Foundation
import Numerics
import QDBMP
Line 10,433:
}
 
canvas.save()</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|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...
<langsyntaxhighlight lang=tcl>package require Tk
 
proc mandelIters {cx cy} {
Line 10,467:
update
}
.mandel configure -cursor {}</langsyntaxhighlight>
 
=={{header|TeX}}==
Line 10,473:
The <code>pst-fractal</code> package includes a Mandelbrot set drawn by emitting [[PostScript]] code (using [[PSTricks]]), so the actual work done in the printer or PostScript interpreter.
 
<langsyntaxhighlight lang=TeX>\input pst-fractal
\psfractal[type=Mandel,xWidth=14cm,yWidth=12cm,maxIter=30,dIter=20] (-2.5,-1.5)(1,1.5)
\end</langsyntaxhighlight>
 
The coordinates are a rectangle in the complex plane to draw, scaled up to <code>xWidth,yWidth</code>.
Line 10,491:
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.
 
<langsyntaxhighlight lang=LaTeX>\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{shadings}
Line 10,498:
\shade[shading=Mandelbrot set] (0,0) rectangle (4,4);
\end{tikzpicture}
\end{document}</langsyntaxhighlight>
 
=={{header|LuaTeX}}==
Line 10,508:
=={{header|TI-83 BASIC}}==
Based on the [[Mandelbrot_set#BASIC|BASIC Version]]. Due to the TI-83's lack of power, it takes around 2 hours to complete at 16 iterations.
<langsyntaxhighlight lang=ti83b>PROGRAM:MANDELBR
:Input "ITER. ",D
:For(A,Xmin,Xmax,ΔX)
Line 10,533:
:End
:End
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 10,540:
Creates same <code>mandelbrot.pgm</code> file.
 
<langsyntaxhighlight lang=txrlisp>(defvar x-centre -0.5)
(defvar y-centre 0.0)
(defvar width 4.0)
Line 10,615:
(put-line "" *stdout*))))
 
(plot)</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
Line 10,665:
56 Print "8"; : Return
57 Print "9"; : Return
64 Print "@"; : Return</langsyntaxhighlight>
Output:
<pre>1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
Line 10,713:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell|4}}
<langsyntaxhighlight lang=bash>((xmin=-8601)) # int(-2.1*4096)
((xmax=2867)) # int( 0.7*4096)
Line 10,737:
done
echo
done</langsyntaxhighlight>
 
{{out}}
Line 10,770:
=={{header|VBScript}}==
VBScript does'nt have access to Windows graphics. I made a class allowing to create a bmp in an array, save it to BMP format and call the default application to view it.
<syntaxhighlight lang=vb>
<lang vb>
option explicit
 
Line 10,968:
Set X = Nothing
 
</syntaxhighlight>
</lang>
=={{header|Vedit macro language}}==
Vedit macro language 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 with '@'.
To compensate the aspect ratio of the font, step sizes in x and y directions are different.
<langsyntaxhighlight lang=vedit>#1 =-21000 // left edge = -2.1
#2 = 15000 // right edge = 1.5
#3 = 15000 // top edge = 1.5
Line 11,006:
}
BOF
</syntaxhighlight>
</lang>
{{out}}
<small>
Line 11,056:
{{trans|Kotlin}}
{{libheader|DOME}}
<langsyntaxhighlight lang=ecmascript>import "graphics" for Canvas, Color
import "dome" for Window
 
Line 11,100:
}
 
var Game = MandelbrotSet.new(800, 600)</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, \screen coordinates of current point
Cnt; \iteration counter
Line 11,128:
X:= ChIn(1); \wait for keystroke
SetVid($03); \restore normal text display
]</langsyntaxhighlight>
{{out}}
[[File:MandelXPL0.png]]
Line 11,138:
{{omit from|M4}}
 
<langsyntaxhighlight lang=xml>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
Line 11,234:
</xsl:stylesheet>
</syntaxhighlight>
</lang>
 
=={{header|Z80 Assembly}}==
<langsyntaxhighlight lang=Z80>
;
; Compute a Mandelbrot set on a simple Z80 computer.
Line 11,478:
ld d, a
ret
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 11,510:
{{trans|XPL0}}
[[File:Mandelbrot.zkl.jpg|300px|thumb|right]]
<langsyntaxhighlight lang=zkl>fcn mandelbrot{ // lord this is slooooow
bitmap:=PPM(640,480);
foreach y,x in ([0..479],[0..639]){
Line 11,529:
}
bitmap.write(File("foo.ppm","wb"));
}();</langsyntaxhighlight>
 
 
305

edits