Mandelbrot set: Difference between revisions
Convert <lang> elements to <syntaxhighlight>
m (Remove unused import.) |
(Convert <lang> elements to <syntaxhighlight>) |
||
Line 13:
{{trans|Python}}
<
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"))</
=={{header|ACL2}}==
<
(+ (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)))</
{{out}}
Line 103:
{{libheader|Lumen}}
mandelbrot.adb:
<
package body Mandelbrot is
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is
Line 142:
end Create_Image;
end Mandelbrot;</
mandelbrot.ads:
<
package Mandelbrot is
Line 151:
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;
end Mandelbrot;</
test_mandelbrot.adb:
<
with Lumen.Window;
with Lumen.Image;
Line 308:
when Program_End =>
null;
end Test_Mandelbrot;</
{{out}}
Line 318:
Plot part of the Mandelbrot set as a pseudo-gif image.
<
INT pix = 300, max iter = 256, REAL zoom = 0.33 / pix;
[-pix : pix, -pix : pix] INT plane;
Line 357:
OD;
close (plot)
</syntaxhighlight>
=={{header|ALGOL W}}==
Generates an ASCII Mandelbrot Set. Translated from the sample program in the Compiler/AST Interpreter task.
<
% 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>
{{out}}
<pre>
Line 452:
Hopper-code & macros Version:
<
#!/usr/bin/hopper
Line 501:
{mandel,"mandel.dat"}save
{0}return
</syntaxhighlight>
Hopper-Basic high level language version:
<
#!/usr/bin/hopper
Line 552:
{mandel,"mandel.dat"}save
{0}return
</syntaxhighlight>
Line 559:
{{trans|Nim}}
<
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 ]</
{{out}}
Line 627:
=={{header|AutoHotkey}}==
<
Width := Height := 400
Line 743:
;---------------------------------------------------------------------------
Return, (r&0xFF)<<16 | g<<8 | b
}</
=={{header|AWK}}==
<
XSize=59; YSize=21;
MinIm=-1.0; MaxIm=1.0;MinRe=-2.0; MaxRe=1.0;
Line 767:
}
exit;
}</
{{out}}
<pre>
Line 796:
This implements a 16bit fixed point arithmetic Mandelbrot set calculation.
{{works with|The Amsterdam Compiler Kit - B|V6.1pre1}}
<
auto cx,cy,x,y,x2,y2;
auto iter;
Line 838:
return(0);
}</
{{out}}
<pre>
Line 873:
{{trans|QBasic}}
<
WINDOW 2,"Mandelbrot",,0,1
Line 920:
' endless loop, use Run -> Stop from the menu to stop program
WHILE (1)
WEND</
==={{header|Applesoft BASIC}}===
This version takes into account the Apple II's funky 280×192 6-color display, which has an effective resolution of only 140×192 in color.
<
10 HGR2
20 XC = -0.5 : REM CENTER COORD X
Line 962:
330 NEXT YS
340 NEXT YI
</syntaxhighlight>
By making the following modifications, the same code will render the Mandelbrot set in monochrome at full 280×192 resolution.
<
150 FOR XS = 0 TO 279
301 C = (C - INT(C/2)*2)*3
310 HCOLOR = C: HPLOT XS, YS
</syntaxhighlight>
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.
<
10MODE5:VDU5
20D%=100 : REM adjust for speed/precision
Line 988:
70PLOT69,X%,Y%
80NEXT
90NEXT</
[[File:Mandelbrot_armbasic.png]]
==={{header|BASIC256}}===
<
graphsize 384,384
Line 1,027:
next x
imgsave "Mandelbrot_BASIC-256.png", "PNG"
</syntaxhighlight>
{{out|Image generated by the script}}
[[File:Mandelbrot BASIC-256.jpg|220px]]
Line 1,033:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
maxiter% = 128
VDU 23,22,sizex%;sizey%;8,8,16,128
Line 1,054:
PLOT X%,Y% : PLOT X%,-Y%
NEXT
NEXT X%</
[[File:Mandelbrot_bbc.gif]]
==={{header|Commander X16 BASIC}}===
<
10 CLS
20 SCREEN $80
Line 1,080:
190 PSET X,YR,I
200 :NEXT:NEXT
</syntaxhighlight>
==={{header|Commodore BASIC}}===
Line 1,090:
Runs in about 90 minutes.
<
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</
===={{header|C-64 with Super Expander 64}}====
Runs in about 4.5 hours.
<
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</
===={{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.
<
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</
===={{header|Commodore 128 (40-column display)}}====
Line 1,164:
64 and Plus/4 versions.
<
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</
===={{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.
<
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</
{{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.
<
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</
{{Out}} VICE screenshot [https://i.imgur.com/y4zYmyD.png here].
Line 1,257:
160 NEXT Y
170 END
</syntaxhighlight>
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,283:
==={{header|FreeBASIC}}===
<
#define zero_x 320
#define zero_y 240
Line 1,338:
while inkey=""
wend
end</
==={{header|GW-BASIC}}===
<
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</
==={{header|Liberty BASIC}}===
Any words of description go outside of lang tags.
<
WindowWidth =440
Line 1,419:
close #w
end
</syntaxhighlight>
==={{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.)
<
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</
==={{header|Microsoft Small Basic}}===
<
GraphicsWindow.Show()
size = 500
Line 1,473:
EndFor
EndFor
</syntaxhighlight>
==={{header|Microsoft Super Extended Color BASIC (Tandy Color Computer 3)}}===
<
1 REM MANDELBROT SET - TANDY COCO 3
2 POKE 65497,1
Line 1,498:
170 NEXT Y
180 GOTO 180
</syntaxhighlight>
==={{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}}
<
10 REM Mandelbrot set
20 CLS
Line 1,547:
510 DATA 27085,14336,-13564,6399,18178,10927
520 DATA -8179,233
</syntaxhighlight>
==={{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.
<
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</
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,594:
==={{header|PureBasic}}===
PureBasic forum: [http://www.purebasic.fr/german/viewtopic.php?f=4&t=22107 discussion]
<
#Window1 = 0
Line 1,651:
Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
EndIf</
[[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.
<
WINDOW (-2, 1.5)-(2, -1.5)
FOR x0 = -2 TO 2 STEP .01
Line 1,684:
PSET (x0, y0), c + 32
NEXT
NEXT</
==={{header|Quite BASIC}}===
<
1000 REM Mandelbrot Set Project
1010 REM Quite BASIC Math Project
Line 1,731:
3090 LET P[8] = "white"
3100 RETURN
</syntaxhighlight>
==={{header|Run BASIC}}===
<
'Based on LibertyBasic solution
'copy the code and go to runbasic.com
Line 1,824:
print "All done, good bye."
end
</syntaxhighlight>
==={{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.
<
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</
==={{Header|SmileBASIC}}===
Generates the points at random, gradually building up the image.
<
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.</
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.
<
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</
==={{header|TI-Basic Color}}===
{{works with|TI-84 Plus CSE, TI-83 Premium CE, TI-84 Plus CE}}
<
ClrDraw
~2->Xmin:1->Xmax:~1->Ymin:1->Ymax
Line 1,902:
End
End
</syntaxhighlight>
==={{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.
<
Function mandel(xi As Double, yi As Double)
Line 1,923:
mandel = i
End Function
</syntaxhighlight>
[[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}}===
<
wid = 4
xcenter = -1: ycenter = 0
Line 1,964:
next ycoord
next xcoord
</syntaxhighlight>
=={{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".
<
@^+1g00,+55_v# !`\+*9<>4v$
@v30p20"?~^"< ^+1g10,+*8<$
Line 1,981:
>*%03 p58*:*/01g"3"* v>::^
\_^#!:-1\+-*2*:*85<^
</syntaxhighlight>
{{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
<
use b
Line 2,044:
w = w*w + c
*px++ = i < max_i ? rainbow(i*359 / rb_i % 360) : black
c += d</
An example plot from the longer version:
Line 2,051:
=={{header|Brainf***}}==
<
A mandelbrot set fractal viewer in brainf*ck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
Line 2,197:
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
</syntaxhighlight>
{{out}}
Line 2,253:
===PPM non interactive===
Here is one file program. It directly creates ppm file.
<
c program:
--------------------------------
Line 2,342:
fclose(fp);
return 0;
}</
===PPM Interactive===
Line 2,351:
{{libheader|GLUT}}
<
#include <stdlib.h>
#include <math.h>
Line 2,590:
glutMainLoop();
return 0;
}</
===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>
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>
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>
/**
ascii Mandelbrot using 16 bits of fixed point integer maths with a selectable fractional precision in bits.
Line 2,738:
</syntaxhighlight>
<pre>
Line 2,813:
=={{header|C sharp|C#}}==
<
using System.Drawing;
using System.Drawing.Imaging;
Line 2,950:
return Re * Re + Im * Im;
}
}</
=={{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.
<
#include <complex>
Line 2,992:
}
}</
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.
<
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");
}</
=={{header|C3}}==
This program produces a BMP as output.
<
extern fn int atoi(char *s);
Line 3,070:
}
}
}</
=={{header|Cixl}}==
Displays a zooming Mandelbrot using ANSI graphics.
<
use: cx;
Line 3,145:
#out show-cursor
normal-mode
</syntaxhighlight>
=={{header|Clojure}}==
{{trans|Perl}}
<
(:refer-clojure :exclude [+ * <])
(:use (clojure.contrib complex-numbers)
Line 3,170:
(println (interpose \newline (map #(apply str %) (partition 80 (mandelbrot)))))
</syntaxhighlight>
=={{header|COBOL}}==
EBCDIC art.
<
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.</
{{out}}
<pre>
Line 3,253:
=={{header|Common Lisp}}==
<
(: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)))</
=={{header|Cowgol}}==
{{trans|B}}
<
const xmin := -8601;
Line 3,335:
print_nl();
cy := cy + dy;
end loop;</
{{out}}
<pre>!!!!!!!!!!!!!!!"""""""""""""####################################""""""""""""""""
Line 3,365:
===Textual Version===
This uses <code>std.complex</code> because D built-in complex numbers are deprecated.
<
import std.stdio, std.complex;
Line 3,377:
writeln;
}
}</
{{out}}
<pre>.......................................................................................
Line 3,431:
===More Functional Textual Version===
The output is similar.
<
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;
}</
===Graphical Version===
{{libheader|QD}} {{libheader|SDL}} {{libheader|Phobos}}
<
double lensqr(cdouble c) { return c.re * c.re + c.im * c.im; }
Line 3,468:
}
while (true) { flip; events; }
}</
=={{header|Dart}}==
Line 3,508:
print(line);
}
}</
=={{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.
<
0.7 sX # xmax = 0.7
Line 3,585:
l2 x # loop
] s2
l2 x</
{{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.
<
32 sM
640 sW 480 sH
Line 3,653:
l2 x
] s2
l2 x</
Line 3,660:
=={{header|DWScript}}==
{{trans|D}}
<
var x, y, i : Integer;
Line 3,676:
end;
PrintLn('');
end;</
=={{header|EasyLang}}==
Line 3,701:
rect 0.4 0.4
.
.</
=={{header|eC}}==
Line 3,709:
Drawing code:
<
{
int x, y;
Line 3,759:
}
}
}</
Interactive class with Rubberband Zoom:
<
{
caption = $"Mandelbrot";
Line 3,895:
}
Mandelbrot mandelbrotForm {};</
=={{header|EchoLisp}}==
<
(lib 'math) ;; fractal function
(lib 'plot)
Line 3,910:
;; result here [http://www.echolalie.org/echolisp/help.html#fractal]
</syntaxhighlight>
=={{header|Elixir}}==
<
def set do
xsize = 59
Line 3,941:
end
Mandelbrot.set</
{{out}}
Line 3,971:
=={{header|Emacs Lisp}}==
===Text mode===
<
(setq mandel-size (cons 76 34))
Line 4,012:
(insert(format "%s" (mandel-iter (mandel-pos x y))))))))
(mandel)</
{{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.)
<
(setq mandel-size (cons 320 300))
Line 4,104:
(insert-image (string-to-image all)))
(mandel-pic)</
=={{header|Erlang}}==
Line 4,115:
[https://github.com/ghulette/mandelbrot-erlang Geoff Hulette's GitHub repository] provides two alternative implementations which are very interesting.
<
-module(mandelbrot).
Line 4,166:
% **************************************************
</syntaxhighlight>
Output:
Line 4,215:
=={{header|ERRE}}==
<
PROGRAM MANDELBROT
Line 4,252:
END FOR
END PROGRAM
</syntaxhighlight>
Note: This is a PC version which uses EGA 16-color 320x200. Graphic commands are taken from
PC.LIB library.
=={{header|F Sharp|F#}}==
<
open System.Windows.Forms
type Complex =
Line 4,316:
let f = new Mandel()
do Application.Run(f)</
=== Alternate version, applicable to text and GUI ===
''' Basic generation code '''
<
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>
''' Text display '''
<
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>
Results:
Line 4,373:
''' Graphics display '''
<
open System.Drawing
open System.Windows.Forms
Line 4,394:
showGraphic toColor 640 480 5000 ((-2.0,1.0),(-1.0,1.0))
</syntaxhighlight>
=={{header|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>
{{out}}
Line 4,466:
=={{header|Fennel}}==
<
#!/usr/bin/env fennel
Line 4,497:
max (arg-def 3 1e5)]
(mandel width height max))
</syntaxhighlight>
=={{header|FOCAL}}==
<
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</
{{output}}
<pre>
Line 4,555:
=={{header|Forth}}==
This uses [[grayscale image]] utilities.
<
: mandel ( gmp F: imin imax rmin rmax -- )
Line 4,578:
80 24 graymap
dup -1e 1e -2e 1e mandel</
{{works with|4tH v3.64}}
This is a completely integer version without local variables, which uses 4tH's native graphics library.
<
640 pic_width ! \ width of the image
Line 4,624:
s" mandelbt.ppm" save_image \ done, save the image
dup gshow
free bye</
=={{header|Fortran}}==
{{Works with|Fortran|90 and later}}
<
implicit none
Line 4,683:
close (10)
end program mandelbrot</
=={{header|Frink}}==
This draws a graphical Mandelbrot set using Frink's built-in graphics and complex arithmetic.
<
// Maximum levels for each pixel.
levels = 60
Line 4,722:
g.show[]
</syntaxhighlight>
=={{header|Furor}}==
<
###sysinclude X.uh
$ff0000 sto szin
Line 4,771:
{ „XRES” }
{ „myscreen” }
</syntaxhighlight>
Line 4,778:
Computes escapes for each pixel, but not the colour.
<
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>
=={{header|FutureBasic}}==
<
_xmin = -8601
_xmax = 2867
Line 4,866:
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Line 4,909:
=={{header|GLSL}}==
Uses smooth coloring.
<
const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
Line 4,960:
}
</syntaxhighlight>
=={{header|gnuplot}}==
The output from gnuplot is controlled by setting the appropriate values for the options <code>terminal</code> and <code>output</code>.
<
set output 'mandelbrot.png'</
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>.
<
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</
{{out}}
[[File:mandelbrot.png]]
Line 4,982:
;Text
Prints an 80-char by 41-line depiction.
<
import "fmt"
Line 5,005:
fmt.Println("")
}
}</
;Graphical
[[File:GoMandelbrot.png|thumb|right|.png image]]
<
import (
Line 5,067:
fmt.Println(err)
}
}</
=={{header|Golfscript}}==
Código sacado de https://codegolf.stackexchange.com/
<
20/3$-@@*10/3$-..*2$.*+1600<}*}32*'
*'=\;\;@@(}60*;(n\}40*;]''+</
{{out}}
<pre>000000000000000000000000000000000000000010000000000000000000
Line 5,119:
=={{header|Hare}}==
{{trans|D}}
<
use math;
Line 5,148:
fn abs(z: complex) f64 = {
return math::sqrtf64(z.re*z.re + z.im*z.im);
};</
{{out}}
<pre>
Line 5,203:
=={{header|Haskell}}==
{{trans|Ruby}}
<
import Data.Complex (Complex ((:+)), magnitude)
Line 5,217:
]
| y <- [1, 0.95 .. -1]
]</
{{Out}}
<pre>
Line 5,257:
'''haskell one-liners :'''
<
-- first attempt
Line 5,272:
-- open GHCI > Copy and paste any of above one-liners > Hit enter
</syntaxhighlight>
A legible variant of the first of the "one-liner" contributions above:
<
main =
putStrLn $
Line 5,307:
)
[".", "\'", ":", "!", "|", "}", "#", " "]
)</
{{Out}}
<pre> #
Line 5,400:
and a legible variant of the last of the "one-liner" contributions above:
<
main =
mapM_
Line 5,419:
else ' '
]
]</
=={{header|Haxe}}==
This version compiles for flash version 9 or greater.
The compilation command is
<
<
{
inline static var MAX_ITER = 255;
Line 5,474:
image.setPixel(x, y, color);
}
}</
=={{header|Huginn}}==
<
exec huginn -E "${0}" "${@}"
#! huginn
Line 5,531:
columns -= 1;
return ( ( lines, columns ) );
}</
{{out}}
Line 5,580:
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main()
Line 5,625:
procedure cAbs(x)
return sqrt(x.r*x.r+x.i*x.i)
end</
{{libheader|Icon Programming Library}}
Line 5,636:
(free implementation: GDL - GNU Data Language
http://gnudatalanguage.sourceforge.net)
<
PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations
Line 5,683:
END
</syntaxhighlight>
from the command line:
<
GDL>.run mandelbrot
</syntaxhighlight>
or
<
GDL> Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200
</syntaxhighlight>
=={{header|Inform 7}}==
{{libheader|Glimmr Drawing Commands by Erik Temple}}
{{works with|Glulx virtual machine}}
<
The story headline is "A Non-Interactive Set".
Line 5,881:
[ fneg n; @bitxor n $80000000 n; return n; ];
#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.
Line 5,889:
=={{header|J}}==
The characteristic function of the Mandelbrot can be defined as follows:
<
The Mandelbrot set can be drawn as follows:
<
load 'viewmat'
viewmat mcf "0 @ domain (_2j_1 1j1) ; 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 [[Mandelbrot_set/J/Output|here]] (The output is HTML-heavy and was split out to make editing this page easier):
<
=={{header|Java}}==
{{libheader|Swing}} {{libheader|AWT}}
<
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
Line 5,944:
new Mandelbrot().setVisible(true);
}
}</
=== Interactive ===
{{libheader|AWT}} {{libheader|Swing}}
<
import static java.awt.Color.black;
import static java.awt.event.KeyEvent.VK_BACK_SLASH;
Line 6,240:
;
}
}</
=={{header|JavaScript}}==
Line 6,249:
The code can be run directly from the Javascript console in modern browsers by copying and pasting it.
<
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);</
{{out}} with default parameters:
Line 6,327:
one for instance with the [https://mbebenita.github.io/WasmExplorer/ WebAssembly explorer]
<
fetch("./mandelIter.wasm")
.then(res => {
Line 6,348:
mandelbrot(canvas, -2, 1, -1, 1, 1000);
// ...
}</
=={{header|jq}}==
Line 6,358:
'''Preliminaries'''
<
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;
</
def Mandeliter( cx; cy; maxiter ):
# [i, x, y, x^2+y^2]
Line 6,412:
svg("mandelbrot"; "100%"; "100%"),
pixies,
"</svg>";</
'''Example''':
<
'''Execution:'''
Line 6,426:
Generates an ASCII representation:
<
z = 0
for i=1:50
Line 6,439:
end
println()
end</
This generates a PNG image file:
<
@inline function hsv2rgb(h, s, v)
Line 6,481:
img = mandelbrot()
save("mandelbrot.png", img)</
===Mandelbrot Set with Julia Animation===
This is an extension of the corresponding R section: e^(-|z|)-smoothing was added.
<
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)</
===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.
<
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")</
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.
<
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")</
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.
<
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")</
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.
<
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")</
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.
<
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])</
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.
<
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])</
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.
<
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")</
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.awt.Graphics
Line 6,801:
fun main(args: Array<String>) {
Mandelbrot().isVisible = true
}</
=={{header|LabVIEW}}==
Line 6,809:
=={{header|Lang5}}==
<
: d2c(*,*) 2 compress 'c dress ; # Make a complex number.
Line 6,823:
iterate abs int 5 min 'print_line apply # Compute & print
</syntaxhighlight>
=={{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.
<
{def mandel
Line 6,864:
{S.serie 0 40}} // y resolution
</syntaxhighlight>
<pre>
Line 6,911:
=={{header|Lasso}}==
<
define mandelbrotBailout => 16
define mandelbrotMaxIterations => 1000
Line 6,963:
mandelbrotTest
</syntaxhighlight>
{{out}}
<small>
Line 7,048:
=={{header|LIL}}==
From the source distribution. Produces a PBM, not shown here.
<
# 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:
}}
}
}</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
cs setpensize [1 1]
make "inc :side/:size
Line 7,147:
end
mandelbrot -2 -1.25 2.5 400</
=={{header|Lua}}==
===Graphical===
Needs LÖVE 2D Engine<br />Zoom in: drag the mouse; zoom out: right click
<
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>
===ASCII===
<
local charmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "@" }
for y = -1.3, 1.3, 0.1 do
Line 7,235:
end
print()
end</
{{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).
<
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
Line 7,308:
}
</syntaxhighlight>
Version 2 without Subroutine. Also there is a screen refresh every 2 seconds.
<
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>
=={{header|Maple}}==
<lang>ImageTools:-Embed(Fractals[EscapeTime]:-Mandelbrot(500, -2.0-1.35*I, .7+1.35*I, output = layer1));</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The implementation could be better. But this is a start...
<
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:
<
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[]] </
Built-in function:
<syntaxhighlight lang
==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.
<
%Define the escape time algorithm
Line 7,424:
shading flat;
end</
To use this function you must specify the:
Line 7,443:
Sample usage:
<
=={{header|Metapost}}==
<
outputtemplate:="%j-%c.svg";
outputformat:="svg";
Line 7,489:
endfig;
end</
Sample usage:
<
=={{header|MiniScript}}==
<
MAX_ITER = 40
gfx.clear color.black
Line 7,514:
end if
end for
end for</
(Will upload an output image as soon as image uploading is fixed.)
=={{header|Modula-3}}==
<
IMPORT Wr, Stdio, Fmt, Word;
Line 7,574:
END;
END;
END Mandelbrot.</
=={{header|MySQL}}==
Line 7,580:
See http://arbitraryscrawl.blogspot.co.uk/2012/06/fractsql.html for an explanation.
<
-- Table to contain all the data points
CREATE TABLE points (
Line 7,677:
INTO OUTFILE '/tmp/image.ppm'
FROM points;
</syntaxhighlight>
=={{header|Nim}}==
Line 7,685:
{{trans|Python}}
<
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)</
{{out}}
Line 7,748:
{{trans|Julia}}
{{libheader|imageman}}
<
import imageman
Line 7,784:
img[x - 1, y - 1] = ColorRGBF64(color)
img.savePNG("mandelbrot.png", compression = 9)</
=={{header|OCaml}}==
<
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;;</
=={{header|Octave}}==
Line 7,820:
This code runs rather slowly and produces coloured Mandelbrot set by accident ([[Media:Mandel-Octave.jpg|output image]]).
<
global width = 200;
global height = 200;
Line 7,853:
endfor
saveimage("mandel.ppm", round(ms .* 255).', "ppm");</
A bit faster than the above implementation
<
function z = mandelbrot()
% to view the image call "image(mandelbrot())"
Line 7,879:
z = abs(z);
end
</syntaxhighlight>
=={{header|Ol}}==
<
(define x-size 59)
(define y-size 21)
Line 7,912:
(print)))
(iota y-size))
</syntaxhighlight>
Output:
Line 7,940:
=={{header|OpenEdge/Progress}}==
<
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.
</
=={{header|PARI/GP}}==
Define function 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());
}</
Output:<pre>gp > mandelbrot()
Line 8,041:
=={{header|Pascal}}==
{{trans|C}}
<
{$IFDEF FPC}
Line 8,136:
close(outfile);
end.</
=={{header|Perl}}==
translation / optimization of the ruby solution
<
sub mandelbrot {
Line 8,154:
{print mandelbrot($x + $y * i) ? ' ' : '#'}
print "\n"
}</
=={{header|Phix}}==
;Ascii
This is included in the distribution (with some extra validation) as demo\mandle.exw
<
-- Mandlebrot set in ascii art demo.
--
Line 8,183:
puts(1,b[remainder(k,16)+1])
end for
end for</
;Graphical
This is included in the distribution as demo\arwendemo\mandel.exw
<
include ..\arwen\dib256.ew
Line 8,426:
WinMain(Main,SW_NORMAL)
void = deleteDib(0)</
=={{header|PHP}}==
Line 8,434:
[[File:Mandel-php.png|thumb|right|Sample output]]
<
$max_x=1;
$min_y=-1;
Line 8,473:
imagepng($im);
imagedestroy($im);
</syntaxhighlight>
=={{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.
<
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]).</
{{out}}
Line 8,562:
=={{header|PicoLisp}}==
<
(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))) ) )</
=={{header|PostScript}}==
<
%%BoundingBox: 0 0 300 200
%%EndComments
Line 8,627:
showpage
origstate restore
%%EOF</
=={{header|PowerShell}}==
<
$x = $y = $i = $j = $r = -16
$colors = [Enum]::GetValues([System.ConsoleColor])
Line 8,651:
Write-Host
}
</syntaxhighlight>
=={{header|Processing}}==
Click on an area to zoom in. Choose areas with multiple colors for interesting zooming.
<
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;
}</
==={{header|Processing Python mode}}===
Click on an area to zoom in.
Choose areas with multiple colors for interesting zooming.
<
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</
=={{header|Prolog}}==
SWI-Prolog has a graphic interface XPCE :
<
mandelbrot :-
Line 8,811:
compute_RGB(CX, CY, Tmp, ZY1, Iter1, IterF).
compute_RGB(_CX, _CY, _ZX, _ZY, Iter, Iter).</
[[FILE:Mandelbrot.jpg]]
Line 8,818:
=={{header|Python}}==
Translation of the ruby solution
<
try:
from functools import reduce
Line 8,836:
print("\n".join("".join(row) for row in rows))
</syntaxhighlight>
A more "Pythonic" version of the code:
<
import math
Line 8,854:
for y in [a * 0.05 for a in range(-20, 20)]])
)
</syntaxhighlight>
Finally, we can also use Matplotlib to visualize the Mandelbrot set with Python:
{{libheader|matplotlib}}
{{libheader|NumPy}}
<
from numpy import NaN
Line 8,883:
ylabel("Im(c)")
savefig("mandelbrot_python.svg")
show()</
Another Numpy version using masks to avoid (explicit) nested loops.
Runs about 16x faster for the same resolution.
<
import numpy as np
Line 8,913:
cmap=plt.cm.prism,
extent=(X.min(), X.max(), Y.min(), Y.max()))
plt.show()</
===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'']).
<
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)</
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.
<
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)</
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.
<
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)</
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.
<
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)</
===Python - "One liner"===
<
print(
'\n'.join(
Line 9,096:
for y in range(-50,50)
))
</syntaxhighlight>
=={{header|R}}==
<
#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)</
===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])
<
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)</
=={{header|Racket}}==
<
#lang racket
Line 9,170:
(mandelbrot 300 200)
</syntaxhighlight>
=={{header|Raku}}==
Line 9,180:
Converted to a .png file for display here.
<
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;
}</
Alternately, a more modern, faster version.
<
my ($w, $h) = 800, 800;
Line 9,279:
} ).map: ((*+$m) * 255).Int]
}
}</
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; an internal character string was used that mimics a part of the ASCII glyph sequence.
<
@ = '>=<;: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. */</
'''output''' 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.
<
@ = '█▓▒░@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. */</
'''output''' using the internal defaults:
<pre>
Line 9,374:
===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.
<
@ = '█▓▒░@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. */</
'''output''' using the internal defaults:
<pre>
Line 9,445:
=={{header|Ring}}==
<
load "guilib.ring"
Line 9,499:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
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].
<
def mandelbrot(a)
Line 9,518:
end
puts
end</
{{trans|Tcl}}
Uses [[Raster graphics operations/Ruby]]
<
require_relative 'raster_graphics'
Line 9,560:
end
Pixmap.mandelbrot(300,300).save('mandel.ppm')</
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby
<
# frozen_string_literal: true
Line 9,603:
size(900, 600)
end
</syntaxhighlight>
=={{header|Rust}}==
Dependencies: image, num-complex
<
extern crate num_complex;
Line 9,647:
// Save image
imgbuf.save("fractal.png").unwrap();
}</
=={{header|Sass/SCSS}}==
<
$canvasWidth: 200;
$canvasHeight: 200;
Line 9,697:
}
</syntaxhighlight>
=={{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.
<
import java.awt.Color
Line 9,745:
else new Color(255, 255, (255*(c-2)).toInt)
}
}</
Read–eval–print loop
<
import javax.swing.ImageIcon
val imgMandel=Mandelbrot.generate()
val mainframe=new MainFrame(){title="Test"; visible=true
contents=new Label(){icon=new ImageIcon(imgMandel.image)}
}</
=={{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.
<
(define y-centre 0.0)
(define width 4.0)
Line 9,796:
(begin (display (pixel i j)) (newline))))))))
(plot)</
=={{header|Scratch}}==
Line 9,873:
=={{header|SenseTalk}}==
<
put 0 into oImag # Imaginary origin
put 0.5 into mag # Magnification
Line 9,935:
close file myFile
</syntaxhighlight>
=={{header|SequenceL}}==
'''SequenceL Code for Computing and Coloring:'''<br>
<
import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;
Line 10,026:
linearInterpolate(v0(0), v1(0), t(0)) := (1 - t) * v0 + t * v1;
//endregion</
'''C++ Driver Code:'''<br>
{{libheader|CImg}}
<
#include "../../../ThirdParty/CImg/CImg.h"
Line 10,132:
return 0;
}</
{{out}}
Line 10,138:
=={{header|Sidef}}==
<
var c = z
{ z = (z*z + c)
Line 10,151:
}
print "\n"
}</
=={{header|Simula}}==
{{trans|Scheme}}
<
REAL XCENTRE, YCENTRE, WIDTH, RMAX, XOFFSET, YOFFSET, PIXELSIZE;
INTEGER N, IMAX, JMAX, COLOURMAX;
Line 10,240:
PLOT;
END;</
=={{header|Spin}}==
Line 10,247:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 10,290:
waitcnt(_clkfreq+cnt)
ser.stop</
{{out}}
Line 10,322:
=={{header|SPL}}==
<
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
.</
Line 10,346:
Using the Swift Numerics package, as well as the C library Quick 'N Dirty BMP imported in Swift.
<
import Numerics
import QDBMP
Line 10,433:
}
canvas.save()</
=={{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...
<
proc mandelIters {cx cy} {
Line 10,467:
update
}
.mandel configure -cursor {}</
=={{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.
<
\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 <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.
<
\usepackage{tikz}
\usetikzlibrary{shadings}
Line 10,498:
\shade[shading=Mandelbrot set] (0,0) rectangle (4,4);
\end{tikzpicture}
\end{document}</
=={{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.
<
:Input "ITER. ",D
:For(A,Xmin,Xmax,ΔX)
Line 10,533:
:End
:End
</syntaxhighlight>
=={{header|TXR}}==
Line 10,540:
Creates same <code>mandelbrot.pgm</code> file.
<
(defvar y-centre 0.0)
(defvar width 4.0)
Line 10,615:
(put-line "" *stdout*))))
(plot)</
=={{header|uBasic/4tH}}==
Line 10,665:
56 Print "8"; : Return
57 Print "9"; : Return
64 Print "@"; : Return</
Output:
<pre>1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
Line 10,713:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell|4}}
<
((xmax=2867)) # int( 0.7*4096)
Line 10,737:
done
echo
done</
{{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>
option explicit
Line 10,968:
Set X = Nothing
</syntaxhighlight>
=={{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.
<
#2 = 15000 // right edge = 1.5
#3 = 15000 // top edge = 1.5
Line 11,006:
}
BOF
</syntaxhighlight>
{{out}}
<small>
Line 11,056:
{{trans|Kotlin}}
{{libheader|DOME}}
<
import "dome" for Window
Line 11,100:
}
var Game = MandelbrotSet.new(800, 600)</
=={{header|XPL0}}==
<
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
]</
{{out}}
[[File:MandelXPL0.png]]
Line 11,138:
{{omit from|M4}}
<
<?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>
=={{header|Z80 Assembly}}==
<
;
; Compute a Mandelbrot set on a simple Z80 computer.
Line 11,478:
ld d, a
ret
</syntaxhighlight>
{{out}}
<pre>
Line 11,510:
{{trans|XPL0}}
[[File:Mandelbrot.zkl.jpg|300px|thumb|right]]
<
bitmap:=PPM(640,480);
foreach y,x in ([0..479],[0..639]){
Line 11,529:
}
bitmap.write(File("foo.ppm","wb"));
}();</
|