Mandelbrot set: Difference between revisions
m
Replace deprecated functions
m (→Normalized Iteration Count, Distance Estimation and Mercator Maps: Code finally shortened and all four examples aligned.) |
m (Replace deprecated functions) |
||
(244 intermediate revisions by 33 users not shown) | |||
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 %
integer leftEdge, rightEdge, topEdge, bottomEdge, xStep, yStep, maxIter;
leftEdge := -420;
Line 400:
end for_y0
end.
</syntaxhighlight>
{{out}}
<pre>
Line 445:
1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
</pre>
[[#M4|The entry for m4]] also is based on Rosetta Code's "compiler" task suite.
=={{header|Amazing Hopper}}==
<p>El siguiente programa genera el conjunto de Mandelbrot directamente en pantalla. Ha sido adaptado desde Wikipedia.</p>
<p>Se ejecutó con:</p>
<p>rxvt -g 500x250 -fn "xft:FantasqueSansMono-Regular:pixelsize=1" -e hopper3 jm/mandel.jambo</p>
<syntaxhighlight lang="amazing hopper">
#!/usr/bin/hopper
#include <jambo.h>
Main
Initialize '300, ancho, alto'
Set '-2,0.47,-1.12,1.12' Init 'min real, max real, min complex, max complex'
Init zero 'submaxRminR, submaxCminC'
Let ( submaxRminR := 'max real' Minus 'min real')
Let ( submaxCminC := 'maxcomplex' Minus 'mincomplex' )
Init zero 'a2,b2,a,b,ta'
Loop for (i=1, Less equal(i, ancho),++i)
Let ( ta := Add(min real, Div (
Loop for (j=1, Less equal
Let ( b := Add( min complex, Div ( Mul (submaxCminC, Minus one(j)), Minus one(alto))) )
k=1000, color=256
Loop if (Sqradd (a,b) Is less than (4), And (k) )
Add(Sqrdiff(a,b), a2),
Add(b2, Mul(2, Mul(a, b)))
Move to (b), Move to (a)
--color
--k
Back
Color back (color), Print("O")
Back
Pause
End
</syntaxhighlight>
{{out}}
[[File:Captura de pantalla de 2022-10-28 15-37-55.png]]
=={{header|Arturo}}==
Line 559 ⟶ 506:
{{trans|Nim}}
<
z: to :complex [0 0]
do.times: 50 [
Line 586 ⟶ 533:
mandelbrot #[ yStart: 1.0 yStep: neg 0.05
xStart: neg 2.0 xStep: 0.0315
height: 40 width: 80 ]</
{{out}}
Line 625 ⟶ 572:
******
**</pre>
=={{header|ATS}}==
===A non-interactive program that writes a PPM image===
{{trans|JavaScript}}
<syntaxhighlight lang="ATS">
(* The algorithm is borrowed from Wikipedia. The graphics is a
modification of the display made by the JavaScript entry. Output
from the program is a Portable Pixmap file. *)
#include "share/atspre_staload.hats"
staload "libats/libc/SATS/math.sats"
staload _ = "libats/libc/DATS/math.dats"
fn
mandel_iter {max_iter : nat}
(cx : double,
cy : double,
max_iter : int max_iter)
:<> intBtwe (0, max_iter) =
let
fun
loop {iter : nat | iter <= max_iter}
.<max_iter - iter>.
(x : double,
y : double,
iter : int iter) :<> intBtwe (0, max_iter) =
if iter = max_iter then
iter
else if 2.0 * 2.0 < (x * x) + (y * y) then
iter
else
let
val x = (x * x) - (y * y) + cx
and y = (2.0 * x * y) + cy
in
loop (x, y, succ iter)
end
in
loop (0.0, 0.0, 0)
end
fn (* Write a Portable Pixmap of the Mandelbrot set. *)
write_mandelbrot_ppm (outf : FILEref,
width : intGte 0,
height : intGte 0,
xmin : double,
xmax : double,
ymin : double,
ymax : double,
max_iter : intGte 0) : void =
let
prval [width : int] EQINT () = eqint_make_gint width
prval [height : int] EQINT () = eqint_make_gint height
macdef output (r, g, b) =
let
val r = min ($UNSAFE.cast{int} ,(r), 255)
and g = min ($UNSAFE.cast{int} ,(g), 255)
and b = min ($UNSAFE.cast{int} ,(b), 255)
in
fprint_val<uchar> (outf, $UNSAFE.cast r);
fprint_val<uchar> (outf, $UNSAFE.cast g);
fprint_val<uchar> (outf, $UNSAFE.cast b);
end
val xscale = (xmax - xmin) / g0i2f width
and yscale = (ymax - ymin) / g0i2f height
fun
loop_y {iy : nat | iy <= height}
.<height - iy>.
(iy : int iy) : void =
if iy <> height then
let
fun
loop_x {ix : nat | ix <= width}
.<width - ix>.
(ix : int ix) : void =
if ix <> width then
let
(* We want to go from top to bottom, left to right. *)
val x = xmin + (xscale * g0i2f ix)
and y = ymin + (yscale * g0i2f (height - iy))
val i = mandel_iter (x, y, max_iter)
(* We can PROVE that "i" is no greater than
"max_iter". *)
prval [i : int] EQINT () = eqint_make_gint i
prval [max_iter : int] EQINT () = eqint_make_gint max_iter
prval () = prop_verify {i <= max_iter} ()
val c = (4.0 * log (g0i2f i)) / log (g0i2f max_iter)
in
if i = max_iter then
output (0, 0, 0)
else if c < 1.0 then
output (0, 0, 255.0 * (c - 1.0))
else if c < 2.0 then
output (0, 255.0 * (c - 1.0), 255)
else
output (255.0 * (c - 2.0), 255, 255);
loop_x (succ ix)
end
in
loop_x 0;
loop_y (succ iy)
end
in
fprintln! (outf, "P6");
fprintln! (outf, width, " ", height);
fprintln! (outf, 255);
loop_y 0
end
implement
main0 () =
let
val outf = stdout_ref
val width = 1024
val height = 1024
val xmin = ~2.25
val xmax = 0.75
val ymin = ~1.5
val ymax = 1.5
val max_iter = 1000
in
write_mandelbrot_ppm (outf, width, height, xmin, xmax,
ymin, ymax, max_iter)
end
</syntaxhighlight>
{{out}}
[[File:Mandelbrot task ATS.png|thumb||none|alt=The Mandelbrot set, displayed in colors.]]
===An interactive program that can write PAM images===
{{trans|ObjectIcon}}
{{trans|Scheme}}
{{libheader|SDL2}}
{{libheader|ats2-xprelude}}
<syntaxhighlight lang="ats">
(*-*- ATS -*-*)
(* This program requires ats2-xprelude:
https://sourceforge.net/p/chemoelectric/ats2-xprelude
Also required is the SDL2 library for C. Not everything in the SDL
interface below is used. The interface is meant to be relatively
safe. For instance, you cannot create a window or renderer without
later destroying it, and you cannot use one at all that was not
properly created. Also you cannot accidentally use an
SDL_WindowEvent as an SDL_TextInputEvent, etc.
The program uses 32+32-bit fixed point to calculate escape times.
One does not need so many bits left of the decimal point, but this
is the fixed point format available from ats2-xprelude.
There are some "FIXME" notes below that refer to a few of the ways
the program could be improved. This is a demo version of something
I am likely to expand into a better program.
Compile the program with (for example)
"myatscc mandelbrot_task_interactive.dats"
##myatsccdef=\
patscc -std=gnu2x -O3 \
-DATS_MEMALLOC_GCBDW \
`pkg-config --define-variable=PATSHOME="${PATSHOME}" \
--cflags sdl2 ats2-xprelude bdw-gc` \
`pkg-config --define-variable=PATSHOME="${PATSHOME}" \
--variable=PATSCCFLAGS ats2-xprelude` \
-o $fname($1) $1 \
`pkg-config --define-variable=PATSHOME="${PATSHOME}" \
--libs sdl2 ats2-xprelude bdw-gc`
*)
(* How to use the program:
Left click : re-center the image
Double left-click : zoom in
Double right-click : zoom out
p or P : save an image as a Portable Arbitrary Map
q or Q : quit the program
The window is resizable.
Closing the window quits the program, just as the Q key does. *)
(*------------------------------------------------------------------*)
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
#include "xprelude/HATS/xprelude.hats"
(* To use 32+32-bit fixed point: *)
staload "xprelude/SATS/fixed32p32.sats"
staload _ = "xprelude/DATS/fixed32p32.dats"
stadef realknd = fix32p32knd
typedef real = fixed32p32
(* Actually, one could use different kinds of real number for
different algorithms: fixed point, floating point,
multiple-precision rational, interval arithmetic, ... even
continued fractions. *)
(*------------------------------------------------------------------*)
(* This is a weak choice of ATS_EXTERN_PREFIX, but will spare us from
having to do a lot of writing. *)
#define ATS_EXTERN_PREFIX ""
extern fn atexit : (() -> void) -> int = "mac#%"
%{^
#define SDL_MAIN_HANDLED 1
#include <SDL.h>
ATSinline() atstype_bool
SDL_bool2ATS (SDL_bool b)
{
return (b == SDL_FALSE) ? atsbool_false : atsbool_true;
}
%}
typedef SDL_bool = $extype"SDL_bool"
extern fn SDL_bool2ATS (b : SDL_bool) :<> bool = "mac#%"
(* - - - - - - - - - - - - - - - - - - - - - - *)
(* Housekeeping. *)
extern fn SDL_SetMainReady () : void = "mac#%"
extern fn SDL_Init (flags : uint32) : void = "mac#%"
extern fn SDL_Quit () : void = "mac#%"
(* - - - - - - - - - - - - - - - - - - - - - - *)
(* Timers. *)
extern fn SDL_Delay (ms : uint32) : void = "mac#%"
(* - - - - - - - - - - - - - - - - - - - - - - *)
(* Video handling. *)
(* Screensavers are disabled by default, except in very early versions
of SDL2. *)
extern fn SDL_DisableScreenSaver () : void = "mac#%"
extern fn SDL_EnableScreenSaver () : void = "mac#%"
extern fn SDL_IsScreenSaverEnabled () : SDL_bool = "mac#%"
absvtype SDL_Window_ptr (p : addr) = ptr p
vtypedef SDL_Window_ptr0 = [p : addr] SDL_Window_ptr p
vtypedef SDL_Window_ptr1 = [p : agz] SDL_Window_ptr p
absvtype SDL_Renderer_ptr (p : addr) = ptr p
vtypedef SDL_Renderer_ptr0 = [p : addr] SDL_Renderer_ptr p
vtypedef SDL_Renderer_ptr1 = [p : agz] SDL_Renderer_ptr p
extern castfn SDL_Window_ptr2ptr :
{p : addr} (!SDL_Window_ptr p) -<> ptr p
extern castfn SDL_Renderer_ptr2ptr :
{p : addr} (!SDL_Renderer_ptr p) -<> ptr p
macdef SDL_INIT_EVENTS = $extval (uint32, "SDL_INIT_EVENTS")
macdef SDL_INIT_TIMER = $extval (uint32, "SDL_INIT_TIMER")
macdef SDL_INIT_VIDEO = $extval (uint32, "SDL_INIT_VIDEO")
macdef SDL_WINDOWPOS_CENTERED = $extval (int, "SDL_WINDOWPOS_CENTERED")
macdef SDL_WINDOWPOS_UNDEFINED = $extval (int, "SDL_WINDOWPOS_UNDEFINED")
macdef SDL_WINDOW_OPENGL = $extval (uint32, "SDL_WINDOW_OPENGL")
macdef SDL_WINDOW_RESIZABLE = $extval (uint32, "SDL_WINDOW_RESIZABLE")
extern fn
SDL_CreateWindow (title : string,
x : int, y : int,
w : int, h : int,
flags : uint32) : SDL_Window_ptr0 = "mac#%"
extern fn
SDL_DestroyWindow : SDL_Window_ptr1 -> void = "mac#%"
fn {}
SDL_DestroyWindow_null
(window : SDL_Window_ptr null) : void =
$UN.castvwtp0{void} window
extern fn
SDL_CreateRenderer (window : !SDL_Window_ptr1,
index : int,
flags : uint32) : SDL_Renderer_ptr0 = "mac#%"
extern fn
SDL_DestroyRenderer : SDL_Renderer_ptr1 -> void = "mac#%"
fn {}
SDL_DestroyRenderer_null
(renderer : SDL_Renderer_ptr null) : void =
$UN.castvwtp0{void} renderer
extern fn
SDL_GetRendererOutputSize (renderer : !SDL_Renderer_ptr1,
w : &int? >> int,
h : &int? >> int) : int = "mac#%"
extern fn
SDL_SetRenderDrawColor (renderer : !SDL_Renderer_ptr1,
r : uint8,
g : uint8,
b : uint8,
a : uint8) : int = "mac#%"
extern fn
SDL_RenderClear (renderer : !SDL_Renderer_ptr1) : int = "mac#%"
extern fn
SDL_RenderDrawPoint (renderer : !SDL_Renderer_ptr1,
x : int,
y : int) : int = "mac#%"
extern fn
SDL_RenderPresent (renderer : !SDL_Renderer_ptr1) : void = "mac#%"
(* - - - - - - - - - - - - - - - - - - - - - - *)
(* Event handling. *)
typedef SDL_Event (t : int) =
$extype_struct"SDL_Event" of
{
type = uint32 t,
timestamp = uint32
}
typedef SDL_Event = [t : int] SDL_Event t
extern fn
SDL_PollEvent (event : &SDL_Event? >> SDL_Event)
: intBtwe (0, 1) = "mac#%"
extern fn
SDL_GetMouseState (x : &int? >> int,
y : &int? >> int) : uint32 = "mac#%"
macdef SDL_BUTTON_LMASK = $extval (uint32, "SDL_BUTTON_LMASK")
macdef SDL_BUTTON_MMASK = $extval (uint32, "SDL_BUTTON_MMASK")
macdef SDL_BUTTON_RMASK = $extval (uint32, "SDL_BUTTON_RMASK")
macdef SDL_BUTTON_X1MASK = $extval (uint32, "SDL_BUTTON_X1MASK")
macdef SDL_BUTTON_X2MASK = $extval (uint32, "SDL_BUTTON_X2MASK")
(* - - - - - - - - - - - - - *)
stacst SDL_QUIT : int
macdef SDL_QUIT = $extval (uint32 SDL_QUIT, "SDL_QUIT")
typedef SDL_QuitEvent =
$extype_struct"SDL_QuitEvent" of
{
type = uint32 SDL_QUIT,
timestamp = uint32
}
extern praxi
SDL_Event2QuitEvent_v :
{p : addr}
SDL_Event SDL_QUIT @ p -<prf>
@(SDL_QuitEvent @ p,
SDL_QuitEvent @ p -<lin,prf> SDL_Event SDL_QUIT @ p)
(* - - - - - - - - - - - - - *)
stacst SDL_WINDOWEVENT : int
macdef SDL_WINDOWEVENT = $extval (uint32 SDL_WINDOWEVENT, "SDL_WINDOWEVENT")
typedef SDL_WindowEvent =
$extype_struct"SDL_WindowEvent" of
{
type = uint32 SDL_WINDOWEVENT,
timestamp = uint32,
windowID = uint32,
event = uint8,
padding1 = uint8,
padding2 = uint8,
padding3 = uint8,
data1 = int32,
data2 = int32
}
extern praxi
SDL_Event2WindowEvent_v :
{p : addr}
SDL_Event SDL_WINDOWEVENT @ p -<prf>
@(SDL_WindowEvent @ p,
SDL_WindowEvent @ p -<lin,prf> SDL_Event SDL_WINDOWEVENT @ p)
macdef SDL_WINDOWEVENT_NONE = $extval (uint8, "SDL_WINDOWEVENT_NONE")
macdef SDL_WINDOWEVENT_SHOWN = $extval (uint8, "SDL_WINDOWEVENT_SHOWN")
macdef SDL_WINDOWEVENT_HIDDEN = $extval (uint8, "SDL_WINDOWEVENT_HIDDEN")
macdef SDL_WINDOWEVENT_EXPOSED = $extval (uint8, "SDL_WINDOWEVENT_EXPOSED")
macdef SDL_WINDOWEVENT_MOVED = $extval (uint8, "SDL_WINDOWEVENT_MOVED")
macdef SDL_WINDOWEVENT_RESIZED = $extval (uint8, "SDL_WINDOWEVENT_RESIZED")
macdef SDL_WINDOWEVENT_SIZE_CHANGED = $extval (uint8, "SDL_WINDOWEVENT_SIZE_CHANGED")
macdef SDL_WINDOWEVENT_MINIMIZED = $extval (uint8, "SDL_WINDOWEVENT_MINIMIZED")
macdef SDL_WINDOWEVENT_MAXIMIZED = $extval (uint8, "SDL_WINDOWEVENT_MAXIMIZED")
macdef SDL_WINDOWEVENT_RESTORED = $extval (uint8, "SDL_WINDOWEVENT_RESTORED")
macdef SDL_WINDOWEVENT_ENTER = $extval (uint8, "SDL_WINDOWEVENT_ENTER")
macdef SDL_WINDOWEVENT_LEAVE = $extval (uint8, "SDL_WINDOWEVENT_LEAVE")
macdef SDL_WINDOWEVENT_FOCUS_GAINED = $extval (uint8, "SDL_WINDOWEVENT_FOCUS_GAINED")
macdef SDL_WINDOWEVENT_FOCUS_LOST = $extval (uint8, "SDL_WINDOWEVENT_FOCUS_LOST")
macdef SDL_WINDOWEVENT_CLOSE = $extval (uint8, "SDL_WINDOWEVENT_CLOSE")
macdef SDL_WINDOWEVENT_TAKE_FOCUS = $extval (uint8, "SDL_WINDOWEVENT_TAKE_FOCUS")
macdef SDL_WINDOWEVENT_HIT_TEST = $extval (uint8, "SDL_WINDOWEVENT_HIT_TEST")
macdef SDL_WINDOWEVENT_ICCPROF_CHANGED = $extval (uint8, "SDL_WINDOWEVENT_ICCPROF_CHANGED")
macdef SDL_WINDOWEVENT_DISPLAY_CHANGED = $extval (uint8, "SDL_WINDOWEVENT_DISPLAY_CHANGED")
(* - - - - - - - - - - - - - *)
stacst SDL_MOUSEMOTION : int
macdef SDL_MOUSEMOTION = $extval (uint32 SDL_MOUSEMOTION, "SDL_MOUSEMOTION")
typedef SDL_MouseMotionEvent =
$extype_struct"SDL_MouseMotionEvent" of
{
type = uint32 SDL_MOUSEMOTION,
timestamp = uint32,
windowID = uint32,
which = uint32,
state = uint32,
x = int32,
y = int32,
xrel = int32,
yrel = int32
}
extern praxi
SDL_Event2MouseMotionEvent_v :
{p : addr}
SDL_Event SDL_MOUSEMOTION @ p -<prf>
@(SDL_MouseMotionEvent @ p,
SDL_MouseMotionEvent @ p -<lin,prf> SDL_Event SDL_MOUSEMOTION @ p)
(* - - - - - - - - - - - - - *)
stacst SDL_MOUSEBUTTONDOWN : int
macdef SDL_MOUSEBUTTONDOWN = $extval (uint32 SDL_MOUSEBUTTONDOWN, "SDL_MOUSEBUTTONDOWN")
stacst SDL_MOUSEBUTTONUP : int
macdef SDL_MOUSEBUTTONUP = $extval (uint32 SDL_MOUSEBUTTONUP, "SDL_MOUSEBUTTONUP")
typedef SDL_MouseButtonEvent (t : int) =
[t == SDL_MOUSEBUTTONDOWN || t == SDL_MOUSEBUTTONUP]
$extype_struct"SDL_MouseButtonEvent" of
{
type = uint32 t,
timestamp = uint32,
windowID = uint32,
which = uint32,
button = uint8,
state = uint8,
clicks = uint8,
padding1 = uint8,
x = int32,
y = int32
}
typedef SDL_MouseButtonEvent = [t : int] SDL_MouseButtonEvent t
extern praxi
SDL_Event2MouseButtonEvent_v :
{p : addr}
{t : int | t == SDL_MOUSEBUTTONDOWN || t == SDL_MOUSEBUTTONUP}
SDL_Event t @ p -<prf>
@(SDL_MouseButtonEvent t @ p,
SDL_MouseButtonEvent t @ p -<lin,prf> SDL_Event t @ p)
macdef SDL_BUTTON_LEFT = $extval (uint8, "SDL_BUTTON_LEFT")
macdef SDL_BUTTON_MIDDLE = $extval (uint8, "SDL_BUTTON_MIDDLE")
macdef SDL_BUTTON_RIGHT = $extval (uint8, "SDL_BUTTON_RIGHT")
macdef SDL_BUTTON_X1 = $extval (uint8, "SDL_BUTTON_X1")
macdef SDL_BUTTON_X2 = $extval (uint8, "SDL_BUTTON_X2")
macdef SDL_PRESSED = $extval (uint8, "SDL_PRESSED")
macdef SDL_RELEASED = $extval (uint8, "SDL_RELEASED")
(* - - - - - - - - - - - - - *)
stacst SDL_TEXTINPUT : int
macdef SDL_TEXTINPUT = $extval (uint32 SDL_TEXTINPUT, "SDL_TEXTINPUT")
#define SDL_TEXTINPUTEVENT_TEXT_SIZE 32
typedef SDL_TextInputEvent =
$extype_struct"SDL_TextInputEvent" of
{
type = uint32 SDL_TEXTINPUT,
timestamp = uint32,
windowID = uint32,
text = @[char][SDL_TEXTINPUTEVENT_TEXT_SIZE]
}
extern praxi
SDL_Event2TextInputEvent_v :
{p : addr}
SDL_Event SDL_TEXTINPUT @ p -<prf>
@(SDL_TextInputEvent @ p,
SDL_TextInputEvent @ p -<lin,prf> SDL_Event SDL_TEXTINPUT @ p)
(*------------------------------------------------------------------*)
exception bailout of string
typedef rgba = @(uint8, uint8, uint8, uint8)
val empty_scene_color =
@(g0i2u 200, g0i2u 200, g0i2u 200, g0i2u 255) : rgba
typedef rgba_array (w : int, h : int) =
matrixref (rgba, w, h)
typedef scene_computer =
{w, h : nat}
(int w, int h, real, real, real) -<cloref1>
rgba_array (w, h)
vtypedef situation (p : addr, q : addr,
w : int, h : int) =
[null < p; null < q; 0 <= w; 0 <= h]
@{window = SDL_Window_ptr p,
renderer = SDL_Renderer_ptr q,
width = int w,
height = int h,
xcenter = real,
ycenter = real,
pixels_per_unit = real,
compute_scene = scene_computer}
vtypedef situation (w : int, h : int) =
[p, q : agz]
situation (p, q, w, h)
vtypedef situation =
[w, h : nat]
situation (w, h)
fn
destroy_situation (situation : situation) : void =
begin
SDL_DestroyRenderer (situation.renderer);
SDL_DestroyWindow (situation.window)
end
fn
get_renderer_size (situation : &situation)
: [renderer_width, renderer_height : nat]
@(int renderer_width, int renderer_height) =
let
var w : int
var h : int
val status = SDL_GetRendererOutputSize (situation.renderer, w, h)
val w = g1ofg0 w and h = g1ofg0 h
in
if (status < 0) + (w < 0) + (h < 0) then
begin
destroy_situation situation;
$raise bailout "rendering error"
end
else
@(w, h)
end
fn
resize_needed (situation : &situation) : bool =
let
val @(w, h) = get_renderer_size situation
in
(w <> situation.width) + (h <> situation.height)
end
(*------------------------------------------------------------------*)
fn
compute_escape_times
{w, h : nat}
{mxtm : nat}
(width : int w,
height : int h,
xcenter : real,
ycenter : real,
pixels_per_unit : real,
max_time : uint16 mxtm)
: matrixref ([tm : nat | tm <= mxtm] uint16 tm, w, h) =
let
typedef tm = [tm : nat | tm <= mxtm] uint16 tm
val times = matrixref_make_elt<tm> (i2sz width, i2sz height,
max_time)
and ppu2 = pixels_per_unit + pixels_per_unit
fun
ij_loop {i, j : nat | i <= w; j <= h}
.<w - i, h - j>.
(i : int i,
j : int j) :<!refwrt> void =
if i = width then
()
else if j = height then
ij_loop (succ i, 0)
else
let
val cx = xcenter + (g0i2f ((i + i) - width) / ppu2)
and cy = ycenter + (g0i2f (height - (j + j)) / ppu2)
fun
tm_loop {tm : nat | tm <= mxtm}
.<mxtm - tm>.
(x : real,
y : real,
xx : real,
yy : real,
tm : uint16 tm)
:<> [tm1 : nat | tm1 <= mxtm] uint16 tm1 =
if tm = max_time then
tm
else if g0i2f 4 < xx + yy then
tm
else
let
val x = xx - yy + cx and y = ((x + x) * y) + cy
val xx = x * x and yy = y * y
in
tm_loop (x, y, xx, yy, succ tm)
end
val tm = tm_loop (g0i2f 0, g0i2f 0,
g0i2f 0, g0i2f 0,
g1i2u 0)
in
times[i, height, j] := tm;
ij_loop (i, succ j)
end
in
ij_loop (0, 0);
times
end
fn
the_durn_simplest_scene_computer
{w, h : nat}
(width : int w,
height : int h,
xcenter : real,
ycenter : real,
pixels_per_unit : real)
:<cloref1> rgba_array (w, h) =
let
val escape_times =
compute_escape_times (width, height, xcenter, ycenter,
pixels_per_unit, g1i2u 255)
and points = matrixref_make_elt<rgba> (i2sz width, i2sz height,
empty_scene_color)
fn {}
time2rgba {tm : nat | tm <= 255}
(tm : uint16 tm) : rgba =
let
val v = (g0u2u (g1i2u 255 - tm)) : uint8
in
@(v, v, v, g0i2u 255)
end
fun
loop {i, j : nat | i <= w; j <= h}
.<w - i, h - j>.
(i : int i,
j : int j) : void =
if i = width then
()
else if j = height then
loop (succ i, 0)
else
begin
points[i, height, j] :=
time2rgba escape_times[i, height, j];
loop (i, succ j)
end
in
loop (0, 0);
points
end
(*------------------------------------------------------------------*)
(* Writing an image to a Portable Arbitrary Map. *)
fn
write_rgba_points_as_pam
{w, h : nat}
(outf : FILEref,
width : int w,
height : int h,
points : rgba_array (w, h)) : void =
let
fun
loop {i, j : nat | i <= w; j <= h}
.<h - j, w - i>.
(i : int i,
j : int j) : void =
if j = height then
()
else if i = width then
loop (0, succ j)
else
let
val @(r, g, b, a) = points[i, height, j]
in
fprint! (outf, int2uchar0 (g0u2i r));
fprint! (outf, int2uchar0 (g0u2i g));
fprint! (outf, int2uchar0 (g0u2i b));
fprint! (outf, int2uchar0 (g0u2i a));
loop (succ i, j)
end
in
(* Portable Arbitrary Map:
https://netpbm.sourceforge.net/doc/pam.html *)
fprintln! (outf, "P7");
fprintln! (outf, "WIDTH ", width);
fprintln! (outf, "HEIGHT ", height);
fprintln! (outf, "DEPTH 4");
fprintln! (outf, "MAXVAL 255");
fprintln! (outf, "TUPLTYPE RGB_ALPHA");
fprintln! (outf, "ENDHDR");
loop (0, 0)
end
(* For this demo, simply number the images, starting at 1 on each run
of the program. *)
val image_number : ref uint = ref 1U
fn
write_image {w, h : nat}
(width : int w,
height : int h,
points : rgba_array (w, h)) : void =
let
val filename =
strptr2string (string_append ("mandelbrot-image-",
tostring_val<uint> !image_number,
".pam"))
in
case+ fileref_open_opt (filename, file_mode_w) of
| ~ None_vt () =>
println! ("ERROR: could not open ", filename, " for writing.")
| ~ Some_vt outf =>
begin
write_rgba_points_as_pam (outf, width, height, points);
fileref_close (outf);
println! ("SUCCESS: wrote ", filename);
!image_number := succ !image_number
end
end
(*------------------------------------------------------------------*)
val initial_width : intGte 0 = 400
val initial_height : intGte 0 = 400
val initial_xcenter : real = g0f2f ~0.75
val initial_ycenter : real = g0f2f 0.0
val initial_pixels_per_unit : real = g0f2f 150.0
val initial_scene_computer : scene_computer =
the_durn_simplest_scene_computer
(* Zoom factor could be adjustable, but is not in this simple demo. *)
val zoom_factor : real = g0f2f 2.0
val min_pixels_per_unit : real = g0f2f 10.0
fn
set_render_rgba (renderer : !SDL_Renderer_ptr1,
rgba : rgba) : int =
let
val @(r, g, b, a) = rgba
in
SDL_SetRenderDrawColor (renderer, r, g, b, a)
end
fn
draw_scene {w, h : nat}
(renderer : !SDL_Renderer_ptr1,
width : int w,
height : int h,
points : rgba_array (w, h)) : void =
let
prval () = mul_gte_gte_gte {w, h} ()
fun
loop {i, j : nat | i <= w; j <= h}
.<w - i, h - j>.
(renderer : !SDL_Renderer_ptr1,
i : int i,
j : int j) : void =
if i = width then
()
else if j = height then
loop (renderer, succ i, 0)
else
let
val rgba = points[i, height, j]
val _ = set_render_rgba (renderer, rgba)
val _ = SDL_RenderDrawPoint (renderer, i, j)
in
loop (renderer, i, succ j)
end
in
ignoret (set_render_rgba (renderer, empty_scene_color));
ignoret (SDL_RenderClear (renderer));
loop (renderer, 0, 0);
end
fnx
situation_changed
{w, h : nat}
(situation : &situation (w, h) >> situation,
event : &SDL_Event? >> SDL_Event) : void =
let
val compute_scene = situation.compute_scene
val points =
compute_scene (situation.width, situation.height,
situation.xcenter, situation.ycenter,
situation.pixels_per_unit)
in
SDL_Delay (g0i2u 16);
event_loop (situation, points, event)
end
and
event_loop {w, h : nat}
(situation : &situation (w, h) >> situation,
points : rgba_array (w, h),
event : &SDL_Event? >> SDL_Event) : void =
let
macdef quit_the_event_loop =
()
macdef present_the_scene =
present_scene (situation, points, event)
macdef deal_with_changed_situation =
situation_changed (situation, event)
macdef write_an_image =
write_image (situation.width, situation.height, points);
in
if resize_needed situation then
let
val @(w, h) = get_renderer_size situation
in
situation.width := w;
situation.height := h;
deal_with_changed_situation
end
else
let
in
draw_scene (situation.renderer,
situation.width, situation.height,
points);
case+ SDL_PollEvent (event) of
| 0 => present_the_scene
| 1 =>
if event.type = SDL_QUIT then
quit_the_event_loop
else if event.type = SDL_WINDOWEVENT then
let
prval @(pf, fpf) = SDL_Event2WindowEvent_v (view@ event)
prval () = view@ event := pf
val window_event = event
prval () = view@ event := fpf (view@ event)
in
if window_event.event = SDL_WINDOWEVENT_SIZE_CHANGED then
deal_with_changed_situation
else if window_event.event = SDL_WINDOWEVENT_CLOSE then
quit_the_event_loop
else
present_the_scene
end
else if event.type = SDL_MOUSEBUTTONDOWN then
let
prval @(pf, fpf) = SDL_Event2MouseButtonEvent_v (view@ event)
prval () = view@ event := pf
val button_event = event
prval () = view@ event := fpf (view@ event)
in
if button_event.button = SDL_BUTTON_LEFT then
begin
if button_event.clicks = g0i2u 1 then
let (* Re-center. *)
val x = g0i2i button_event.x
and y = g0i2i button_event.y
and w = situation.width
and h = situation.height
and ppu = situation.pixels_per_unit
val ppu2 = ppu + ppu
in
situation.xcenter :=
situation.xcenter + (g0i2f (x + x - w) / ppu2);
situation.ycenter :=
situation.ycenter + (g0i2f (h - y - y) / ppu2);
deal_with_changed_situation
end
else
let (* Zoom in. *)
val new_ppu = situation.pixels_per_unit * zoom_factor
in
situation.pixels_per_unit := new_ppu;
deal_with_changed_situation
end
end
else if button_event.button = SDL_BUTTON_RIGHT then
begin
if button_event.clicks = g0i2u 1 then
present_the_scene
else
let (* Zoom out *)
val new_ppu = situation.pixels_per_unit / zoom_factor
in
if min_pixels_per_unit <= new_ppu then
situation.pixels_per_unit := new_ppu;
deal_with_changed_situation
end
end
else
present_the_scene
end
else if event.type = SDL_TEXTINPUT then
let
prval @(pf, fpf) = SDL_Event2TextInputEvent_v (view@ event)
prval () = view@ event := pf
var text_event = event
prval () = view@ event := fpf (view@ event)
macdef text = text_event.text
in
case+ @(text[0], text[1]) of
| @('q', '\0') => quit_the_event_loop
| @('Q', '\0') => quit_the_event_loop
| @('p', '\0') =>
begin
write_an_image;
present_the_scene
end
| @('P', '\0') =>
begin
write_an_image;
present_the_scene
end
| _ => present_the_scene
end
else
present_the_scene
end
end
and
present_scene {w, h : nat}
(situation : &situation (w, h) >> situation,
points : rgba_array (w, h),
event : &SDL_Event? >> SDL_Event) : void =
begin
SDL_RenderPresent (situation.renderer);
SDL_Delay (g0i2u 16);
event_loop (situation, points, event)
end
fn
run_program () : void =
let
(* FIXME: For best form, we should also set up a signal handler
that runs SDL_Quit, so the display does not get stuck in an
undesired state even if the program crashes. For instance,
there could be a signaled divide by zero or overflow event. And
we are at least changing whether the screensaver is enabled. *)
val _ = atexit SDL_Quit
val () = SDL_Init (SDL_INIT_EVENTS
lor SDL_INIT_TIMER
lor SDL_INIT_VIDEO)
(* FIXME: Find out whether the screensaver was enabled BEFORE we
started SDL2, and set SDL2 to whichever setting it was. *)
val () = SDL_EnableScreenSaver ()
val window = SDL_CreateWindow ("mandelbrot_task_interactive",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
initial_width, initial_height,
SDL_WINDOW_RESIZABLE)
val p_window = SDL_Window_ptr2ptr window
prval () = lemma_ptr_param p_window
in
if iseqz p_window then
begin
SDL_DestroyWindow_null window;
$raise bailout "failed to initialize a window"
end
else
let
val renderer = SDL_CreateRenderer (window, ~1, g0i2u 0)
val p_renderer = SDL_Renderer_ptr2ptr renderer
prval () = lemma_ptr_param p_renderer
in
if iseqz p_renderer then
begin
SDL_DestroyRenderer_null renderer;
SDL_DestroyWindow window;
$raise bailout "failed to initialize a renderer"
end
else
let
var situation : situation =
@{window = window,
renderer = renderer,
width = initial_width,
height = initial_height,
xcenter = initial_xcenter,
ycenter = initial_ycenter,
pixels_per_unit = initial_pixels_per_unit,
compute_scene = initial_scene_computer}
var event : SDL_Event?
in
situation_changed (situation, event);
destroy_situation situation
end
end
end
implement
main () =
try
begin
SDL_SetMainReady ();
run_program ();
0
end
with
| ~ bailout msg =>
begin
println! ("Error: ", msg);
1
end
(*------------------------------------------------------------------*)
</syntaxhighlight>
{{out}}
A snapshot image of part of the set:
[[File:Mantelbrot task interactive dats sampleimage.png|thumb|none|alt=A portion of the Mandelbrot set, in shades of gray and black.]]
=={{header|AutoHotkey}}==
<
Width := Height := 400
Line 743 ⟶ 1,732:
;---------------------------------------------------------------------------
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 ⟶ 1,756:
}
exit;
}</
{{out}}
<pre>
Line 796 ⟶ 1,785:
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 ⟶ 1,827:
return(0);
}</
{{out}}
<pre>
Line 867 ⟶ 1,856:
!!!!!!!!!!!!!!!""""""""""""#####################################""""""""""""""""
</pre>
=={{header|bc}}==
[[File:Mandelbrot-bc.jpg|thumb|right]]
Producing a [https://fr.wikipedia.org/wiki/Portable_pixmap PGM] image.
To work properly, this needs to run with the environment variable BC_LINE_LENGTH set to 0.
<syntaxhighlight lang=bc>max_iter = 50
width = 400; height = 401
scale = 10
xmin = -2; xmax = 1/2
ymin = -5/4; ymax = 5/4
define mandelbrot(c_re, c_im) {
auto i
# z = 0
z_re = 0; z_im = 0
z2_re = 0; z2_im = 0
for (i=0; i<max_iter; i++) {
# z *= z
z_im = 2*z_re*z_im
z_re = z2_re - z2_im
# z += c
z_re += c_re
z_im += c_im
# z2 = z.*z
z2_re = z_re*z_re
z2_im = z_im*z_im
if (z2_re + z2_im > 4) return i
}
return 0
}
print "P2\n", width, " ", height, "\n255\n"
for (i = 0; i < height; i++) {
y = ymin + (ymax - ymin) / height * i
for (j = 0; j < width; j++) {
x = xmin + (xmax - xmin) / width * j
tmp_scale = scale
scale = 0
m = (255 * mandelbrot(x, y) + max_iter + 1) / max_iter
print m
if ( j < width - 1 ) print " "
scale = tmp_scale
}
print "\n"
}
quit</syntaxhighlight>
=={{header|BASIC}}==
Line 873 ⟶ 1,916:
{{trans|QBasic}}
<
WINDOW 2,"Mandelbrot",,0,1
Line 920 ⟶ 1,963:
' 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 ⟶ 2,005:
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 ⟶ 2,021:
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 ⟶ 2,031:
70PLOT69,X%,Y%
80NEXT
90NEXT</
[[File:Mandelbrot_armbasic.png]]
==={{header|BASIC256}}===
<
graphsize 384,384
Line 1,027 ⟶ 2,070:
next x
imgsave "Mandelbrot_BASIC-256.png", "PNG"
</syntaxhighlight>
{{out|Image generated by the script}}
[[File:Mandelbrot BASIC-256.jpg|220px]]
Line 1,033 ⟶ 2,076:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
maxiter% = 128
VDU 23,22,sizex%;sizey%;8,8,16,128
Line 1,054 ⟶ 2,097:
PLOT X%,Y% : PLOT X%,-Y%
NEXT
NEXT X%</
[[File:Mandelbrot_bbc.gif]]
==={{header|Commander X16 BASIC}}===
<syntaxhighlight lang="x16basic">
10 CLS
20 SCREEN $80
Line 1,080 ⟶ 2,123:
190 PSET X,YR,I
200 :NEXT:NEXT
</syntaxhighlight>
==={{header|Commodore BASIC}}===
Line 1,090 ⟶ 2,133:
Runs in about 90 minutes.
<
110 COLOR 1,3,0,0:GRAPHIC 2:TH=20
120 FOR PY=0 TO 80
Line 1,110 ⟶ 2,153:
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 ⟶ 2,176:
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 ⟶ 2,198:
250 NEXT PY
260 GETKEY K$
270 GRAPHIC 0</
===={{header|Commodore 128 (40-column display)}}====
Line 1,164 ⟶ 2,207:
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 ⟶ 2,225:
260 SLOW:GRAPHIC 1
270 GETKEY K$
280 GRAPHIC 0</
===={{header|Commodore 128 (80-column display)}}====
Line 1,189 ⟶ 2,232:
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 ⟶ 2,250:
250 NEXT PY
260 GETKEY K$
270 @TEXT</
{{Out}}
Line 1,215 ⟶ 2,258:
===={{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 ⟶ 2,277:
270 NEXT I
280 IF I>TH THEN I=TH
290 RETURN</
{{Out}} VICE screenshot [https://i.imgur.com/y4zYmyD.png here].
Line 1,240 ⟶ 2,283:
==={{header|DEC BASIC-PLUS}}===
Works under RSTS/E v7.0 on the [[wp:SIMH|simh]] PDP-11 emulator. For installation procedures for RSTS/E, see [http://www.eecis.udel.edu/~mader/delta/downloadrsts.html here].
<syntaxhighlight lang="basic">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,257 ⟶ 2,300:
160 NEXT Y
170 END
</syntaxhighlight>
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,283 ⟶ 2,326:
==={{header|FreeBASIC}}===
<
#define zero_x 320
#define zero_y 240
Line 1,338 ⟶ 2,381:
while inkey=""
wend
end</
==={{header|GW-BASIC}}===
<
20 ZEROY = 100 : MAXIT = 32
30 SCREEN 1
Line 1,360 ⟶ 2,403:
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 ⟶ 2,462:
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 ⟶ 2,483:
15 PLOT xp, yp, c MOD 16
16 NEXT
17 NEXT</
==={{header|Microsoft Small Basic}}===
<syntaxhighlight lang="small basic">
GraphicsWindow.Show()
size = 500
Line 1,473 ⟶ 2,516:
EndFor
EndFor
</syntaxhighlight>
==={{header|Microsoft Super Extended Color BASIC (Tandy Color Computer 3)}}===
<syntaxhighlight lang="coco3basic">
1 REM MANDELBROT SET - TANDY COCO 3
2 POKE 65497,1
Line 1,498 ⟶ 2,541:
170 NEXT Y
180 GOTO 180
</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{trans|Microsoft Super Extended Color BASIC}}
<syntaxhighlight lang="qbasic">100 SCREEN 2
110 CLS
120 x1 = 256 : y1 = 192
130 i1 = -1 : i2 = 1
140 r1 = -2 : r2 = 1
150 s1 = (r2-r1)/x1 : s2 = (i2-i1)/y1
160 FOR y = 0 TO y1
170 i3 = i1+s2*y
180 FOR x = 0 TO x1
190 r3 = r1+s1*x
200 z1 = r3 : z2 = i3
210 FOR n = 0 TO 30
220 a = z1*z1 : b = z2*z2
230 IF a+b > 4 GOTO 270
240 z2 = 2*z1*z2+i3
250 z1 = a-b+r3
260 NEXT n
270 PSET (x,y),n-16*INT(n/16)
280 NEXT x
290 NEXT y
300 GOTO 300</syntaxhighlight>
{{out}}
[[File:Mandelbrot-MS-BASIC.png]]
==={{header|Nascom BASIC}}===
Line 1,508 ⟶ 2,578:
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 ⟶ 2,617:
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 ⟶ 2,637:
150 PRINT
160 NEXT Y
170 END</
{{out}}
<pre>>>>>>>=====<<<<<<<<<<<<<<<;;;;;;:::96032:;;;;<<<<===========
Line 1,594 ⟶ 2,664:
==={{header|PureBasic}}===
PureBasic forum: [http://www.purebasic.fr/german/viewtopic.php?f=4&t=22107 discussion]
<
#Window1 = 0
Line 1,651 ⟶ 2,721:
Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
EndIf</
[[File:Mandelbrot-PureBasic.png]]
Line 1,657 ⟶ 2,727:
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 ⟶ 2,754:
PSET (x0, y0), c + 32
NEXT
NEXT</
==={{header|Quite BASIC}}===
<
1000 REM Mandelbrot Set Project
1010 REM Quite BASIC Math Project
Line 1,731 ⟶ 2,801:
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 ⟶ 2,894:
print "All done, good bye."
end
</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
Line 1,831 ⟶ 2,901:
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 ⟶ 2,915:
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 ⟶ 2,928:
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 ⟶ 2,952:
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}}
<syntaxhighlight lang="ti-basic">
ClrDraw
~2->Xmin:1->Xmax:~1->Ymin:1->Ymax
Line 1,901 ⟶ 2,971:
Pt-On(real(C),imag(C),N
End
End</syntaxhighlight>
==={{header|True BASIC}}===
{{trans|Microsoft Super Extended Color BASIC}}
<syntaxhighlight lang="qbasic">SET WINDOW 0, 256, 0, 192
LET x1 = 256/2
LET y1 = 192/2
LET i1 = -1
LET i2 = 1
LET r1 = -2
LET r2 = 1
LET s1 = (r2-r1) / x1
LET s2 = (i2-i1) / y1
FOR y = 0 TO y1 STEP .05
LET i3 = i1 + s2 * y
FOR x = 0 TO x1 STEP .05
LET r3 = r1 + s1 * x
LET z1 = r3
LET z2 = i3
FOR n = 0 TO 30
LET a = z1 * z1
LET b = z2 * z2
IF a+b > 4 THEN EXIT FOR
LET z2 = 2 * z1 * z2 + i3
LET z1 = a - b + r3
NEXT n
SET COLOR n - 16*INT(n/16)
PLOT POINTS: x,y
NEXT x
NEXT y
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.
<syntaxhighlight lang="vba">Function mandel(xi As Double, yi As Double)
maxiter = 256
Line 1,922 ⟶ 3,022:
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 ⟶ 3,063:
next ycoord
next xcoord
</syntaxhighlight>
=={{header|Befunge}}==
Line 1,971 ⟶ 3,070:
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 ⟶ 3,080:
>*%03 p58*:*/01g"3"* v>::^
\_^#!:-1\+-*2*:*85<^
</syntaxhighlight>
{{out}}
Line 2,028 ⟶ 3,127:
=={{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 ⟶ 3,143:
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 ⟶ 3,150:
=={{header|Brainf***}}==
<syntaxhighlight lang="brainf***">
A mandelbrot set fractal viewer in brainf*ck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
Line 2,197 ⟶ 3,296:
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
</syntaxhighlight>
{{out}}
Line 2,253 ⟶ 3,352:
===PPM non interactive===
Here is one file program. It directly creates ppm file.
<
c program:
--------------------------------
Line 2,342 ⟶ 3,441:
fclose(fp);
return 0;
}</
===PPM Interactive===
Line 2,351 ⟶ 3,450:
{{libheader|GLUT}}
The following version should work on architectures (such as x86/x86-64) that allow unaligned pointers.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 2,590 ⟶ 3,692:
glutMainLoop();
return 0;
}</
Here is a variant that hopefully will work on a broader range of architectures, although it has been tested only on x86-64.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
void set_texture();
unsigned char *tex;
int gwin;
GLuint texture;
int width, height;
int old_width, old_height;
double scale = 1. / 256;
double cx = -.6, cy = 0;
int color_rotate = 0;
int saturation = 1;
int invert = 0;
int max_iter = 256;
void render()
{
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBindTexture(GL_TEXTURE_2D, texture);
glBegin(GL_QUADS);
glTexCoord2d(0, 0);
glVertex2i(0, 0);
glTexCoord2d(1, 0);
glVertex2i(width, 0);
glTexCoord2d(1, 1);
glVertex2i(width, height);
glTexCoord2d(0, 1);
glVertex2i(0, height);
glEnd();
glFlush();
glFinish();
}
int dump = 1;
void screen_dump()
{
char fn[100];
sprintf(fn, "screen%03d.ppm", dump++);
FILE *fp = fopen(fn, "w");
fprintf(fp, "P6\n%d %d\n255\n", width, height);
for (int i = height - 1; i >= 0; i -= 1) {
for (int j = 0; j < width; j += 1) {
fwrite(&tex[((i * width) + j) * 4], 1, 3, fp);
}
}
fclose(fp);
printf("%s written\n", fn);
}
void keypress(unsigned char key,[[maybe_unused]]
int x,[[maybe_unused]]
int y)
{
switch (key) {
case 'q':
glFinish();
glutDestroyWindow(gwin);
break;
case 27:
scale = 1. / 256;
cx = -.6;
cy = 0;
set_texture();
break;
case 'r':
color_rotate = (color_rotate + 1) % 6;
set_texture();
break;
case '>':
case '.':
max_iter += 128;
if (max_iter > 1 << 15)
max_iter = 1 << 15;
printf("max iter: %d\n", max_iter);
set_texture();
break;
case '<':
case ',':
max_iter -= 128;
if (max_iter < 128)
max_iter = 128;
printf("max iter: %d\n", max_iter);
set_texture();
break;
case 'c':
saturation = 1 - saturation;
set_texture();
break;
case 's':
screen_dump();
break;
case 'z':
max_iter = 4096;
set_texture();
break;
case 'x':
max_iter = 128;
set_texture();
break;
case ' ':
invert = !invert;
set_texture();
break;
default:
set_texture();
break;
}
}
#define VAL 255
void hsv_to_rgba(int hue, int min, int max, unsigned char *px)
{
unsigned char r;
unsigned char g;
unsigned char b;
if (min == max)
max = min + 1;
if (invert)
hue = max - (hue - min);
if (!saturation) {
r = 255 * (max - hue) / (max - min);
g = r;
b = r;
} else {
double h =
fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6);
double c = VAL * saturation;
double X = c * (1 - fabs(fmod(h, 2) - 1));
r = 0;
g = 0;
b = 0;
switch ((int) h) {
case 0:
r = c;
g = X;
break;
case 1:
r = X;
g = c;
break;
case 2:
g = c;
b = X;
break;
case 3:
g = X;
b = c;
break;
case 4:
r = X;
b = c;
break;
default:
r = c;
b = X;
break;
}
}
/* Using an alpha channel neatly solves the problem of aligning
* rows on 4-byte boundaries (at the expense of memory, of
* course). */
px[0] = r;
px[1] = g;
px[2] = b;
px[3] = 255; /* Alpha channel. */
}
void calc_mandel()
{
int i, j, iter, min, max;
double x, y, zx, zy, zx2, zy2;
unsigned short *hsv = malloc(width * height * sizeof(unsigned short));
min = max_iter;
max = 0;
for (i = 0; i < height; i++) {
y = (i - height / 2) * scale + cy;
for (j = 0; j < width; j++) {
x = (j - width / 2) * scale + cx;
iter = 0;
zx = hypot(x - .25, y);
if (x < zx - 2 * zx * zx + .25)
iter = max_iter;
if ((x + 1) * (x + 1) + y * y < 1 / 16)
iter = max_iter;
zx = 0;
zy = 0;
zx2 = 0;
zy2 = 0;
while (iter < max_iter && zx2 + zy2 < 4) {
zy = 2 * zx * zy + y;
zx = zx2 - zy2 + x;
zx2 = zx * zx;
zy2 = zy * zy;
iter += 1;
}
if (iter < min)
min = iter;
if (iter > max)
max = iter;
hsv[(i * width) + j] = iter;
}
}
for (i = 0; i < height; i += 1) {
for (j = 0; j < width; j += 1) {
unsigned char *px = tex + (((i * width) + j) * 4);
hsv_to_rgba(hsv[(i * width) + j], min, max, px);
}
}
free(hsv);
}
void alloc_tex()
{
if (tex == NULL || width != old_width || height != old_height) {
free(tex);
tex = malloc(height * width * 4 * sizeof(unsigned char));
memset(tex, 0, height * width * 4 * sizeof(unsigned char));
old_width = width;
old_height = height;
}
}
void set_texture()
{
alloc_tex();
calc_mandel();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
render();
}
void mouseclick(int button, int state, int x, int y)
{
if (state != GLUT_UP)
return;
cx += (x - width / 2) * scale;
cy -= (y - height / 2) * scale;
switch (button) {
case GLUT_LEFT_BUTTON: /* zoom in */
if (scale > fabs((double) x) * 1e-16
&& scale > fabs((double) y) * 1e-16)
scale /= 2;
break;
case GLUT_RIGHT_BUTTON: /* zoom out */
scale *= 2;
break;
/* any other button recenters */
}
set_texture();
}
void resize(int w, int h)
{
printf("resize %d %d\n", w, h);
width = w;
height = h;
glViewport(0, 0, w, h);
glOrtho(0, w, 0, h, -1, 1);
set_texture();
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(640, 480);
gwin = glutCreateWindow("Mandelbrot");
glutDisplayFunc(render);
glutKeyboardFunc(keypress);
glutMouseFunc(mouseclick);
glutReshapeFunc(resize);
glGenTextures(1, &texture);
set_texture();
}
int main(int c, char **v)
{
tex = NULL;
init_gfx(&c, v);
printf
("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t"
"<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n");
glutMainLoop();
return 0;
}
// local variables:
// mode: C
// c-file-style: "k&r"
// c-basic-offset: 4
// end:
</syntaxhighlight>
''(PLEASE FIXME: Does resizing work correctly, in either version?)''
===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,632 ⟶ 4,081:
.........::::::::::::::::::::::::::::::::::::::::::::::::::::::::...................
.............::::::::::::::::::::::::::::::::::::::::::::::::.......................
</pre>
===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.
This is still only 16 bits mathc and allocating more than 6 bits of fractional precision leads to an overflow that adds noise to the plot..
This code frequently casts to short to ensure we're not accidentally benefitting from GCC promotion from short 16 bits to int.
gcc fixedPoint.c -lm
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
short s(short i);
short toPrec(double f, int bitsPrecision);
int main(int argc, char* argv[])
{
// chosen to match https://www.youtube.com/watch?v=DC5wi6iv9io
int width = 32; // basic width of a zx81
int height = 22; // basic width of a zx81
int zoom=3; // bigger with finer detail ie a smaller step size - leave at 1 for 32x22
// params
short bitsPrecision = 6;
printf("PRECISION=%d\n", bitsPrecision);
short X1 = toPrec(3.5,bitsPrecision) / zoom;
short X2 = toPrec(2.25,bitsPrecision) ;
short Y1 = toPrec(3,bitsPrecision)/zoom ; // horiz pos
short Y2 = toPrec(1.5,bitsPrecision) ; // vert pos
short LIMIT = toPrec(4,bitsPrecision);
// fractal
//char * chr = ".:-=X$#@.";
char * chr = "abcdefghijklmnopqr ";
//char * chr = ".,'~=+:;[/<&?oxOX#.";
short maxIters = strlen(chr);
short py=0;
while (py < height*zoom) {
short px=0;
while (px < width*zoom) {
short x0 = s(s(px*X1) / width) - X2;
short y0 = s(s(py*Y1) / height) - Y2;
short x=0;
short y=0;
short i=0;
short xSqr;
short ySqr;
while (i < maxIters) {
xSqr = s(x * x) >> bitsPrecision;
ySqr = s(y * y) >> bitsPrecision;
// Breakout if sum is > the limit OR breakout also if sum is negative which indicates overflow of the addition has occurred
// The overflow check is only needed for precisions of over 6 bits because for 7 and above the sums come out overflowed and negative therefore we always run to maxIters and we see nothing.
// By including the overflow break out we can see the fractal again though with noise.
if ((xSqr + ySqr) >= LIMIT || (xSqr+ySqr) < 0) {
break;
}
short xt = xSqr - ySqr + x0;
y = s(s(s(x * y) >> bitsPrecision) * 2) + y0;
x=xt;
i = i + 1;
}
i = i - 1;
printf("%c", chr[i]);
px = px + 1;
}
printf("\n");
py = py + 1;
}
}
// convert decimal value to a fixed point value in the given precision
short toPrec(double f, int bitsPrecision) {
short whole = ((short)floor(f) << (bitsPrecision));
short part = (f-floor(f))*(pow(2,bitsPrecision));
short ret = whole + part;
return ret;
}
// convenient casting
short s(short i) {
return i;
}
</syntaxhighlight>
<pre>
$ gcc fixedPoint.c -lm && ./a.out
PRECISION=6
aaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcdcccbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccddcbbbbb
aaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbegfcdbbb
aaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbdccedbb
aaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbdcccb
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbcfdddcccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbdded
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbcccccddfcccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccc
aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbcccccdeccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbcc
aaaaaaaaaaaaaaaaabbbbbbbbbbfcccccddeccccccccccccccccdddddeeeddddccccccbbbbbbbbbbbbbbbbbbbbbbbbbe
aaaaaaaaaaaaaaaabbbbbbbbbbcccccdddccccccccccccccdeddddeefigeeeddddecccccbbbbbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaabbbbbbbecccccdddcccccccccccccdddddddddeefhmgfffddddedcccccbbbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaabbbbbbbcccccccdcccccccccccccccdgddddddfeefgjpijjfdddddedccccccbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaabbbbbccccccdedccccccccccccccdddddddddeeefgkj ojgfedddddeccccccbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaabbbbbcccccegeccccccccccccccdeedddddddeeeeghhkp hgheefddddecccccccbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaabbbbccccceddcccccccccccccccfddddddddeeeeefmlkr ihheeeedddddgccccccbbbbbbbbbbbbbbbb
aaaaaaaaaaaaabbbccccddfcccccccccccccccedddddddddeeegffhnp rpjffeeeiddddcccccccbbbbbbbbbbbbbbb
aaaaaaaaaaaabbbcccddecccccccccccccccddddddddddeeffffgghm jgffeeeegdddccccccccbbbbbbbbbbbbb
aaaaaaaaaaabbbccdedccccccccccccccccdddddddddeefffffgghil khggffffeeeddccccccccbbbbbbbbbbbb
aaaaaaaaaaabbccdeccccccccccccccccddddddddeeef ijjhhhkijlo qkihjhgffgngeddcccccccbbbbbbbbbbbb
aaaaaaaaaabbcddccccccccccccccccdddddddfeeeefgjq lkk p n khhhiqifedcccccccdbbbbbbbbbbb
aaaaaaaaaabbccccccccccccccccccddddddefeeeeffgilq plk rrqgeddcccccccdbbbbbbbbbb
aaaaaaaaaabdccccccccccccccccdddhegeeeeeefffghiq mfeeddcccccccdbbbbbbbbb
aaaaaaaaaaccccccccccccccccdddeeeeeeeeeeffffhjklp phfeeddcccccccdcbbbbbbbb
aaaaaaaaabcccccccccccccddddegeeeeeeeeeffffhppp jgggedddccccccccbbbbbbbb
aaaaaaaaabccccccccccddddeefpifffffffffggggik hgfedddcccccccdcbbbbbbb
aaaaaaaaaccccccceddddddeeifl hgggjrhggggghj p qjnfdddcccccccdcbbbbbbb
aaaaaaaabccccddedddddefeefghqnokkloqiqhhhik ifdddcccccccdcbbbbbbb
aaaaaaaaccceddddddddgfeeffghir o n qmjiijo igfedddcccccccccbbbbbb
aaaaaaaaccddedddddeeeeeefgghkq lll lgfddddcccccccdcbbbbbb
aaaaaaaacddddddddeeeeeefhgjol rn geddddcccccccdcbbbbbb
aaaaaaaaedddddddeeeffggojjll hfeddddeccccccdcbbbbbb
aaaaaaaaddddddefffffggmkopmop ngfefdddfccccccdcbbbbbb
aaaaaaaaeeffgihggiihikk hfeefdddeccccccddbbbbbb
aaaaaaaa kigfgefdddecccccceebbbbbb
aaaaaaaaeeffhgjggghhhklqm ligfhefdddeccccccddbbbbbb
aaaaaaaaddddddefffffgggirq hffefdddeccccccdebbbbbb
aaaaaaaahdddddddeefgfggilkjk hfeedddeccccccddbbbbbb
aaaaaaaacddddddddeeeeeefhhhkl lfefdddeccccccdcbbbbbb
aaaaaaaaccddedddddefeeeeffgijo on qfedddcccccccdcbbbbbb
aaaaaaaabcceddddddddegeeefggik r kko jhfedddcccccccdcbbbbbb
aaaaaaaabccccddddddddefeeefijmk jkp kmiijlq qhfedddcccccccccbbbbbb
aaaaaaaaacccccccdddddddeeefh hhghi kjggghil r geddcccccccdcbbbbbbb
aaaaaaaaabccccccccccdddddefgnfgffghggggggghjm lj feddcccccccdcbbbbbbb
aaaaaaaaabccccccccccccccdddeffggeeeefffffggm igfefddcccccccdbbbbbbbb
aaaaaaaaaaccccccccccccccccdddeeeeeeeeeeffffhjm kgfeddcccccccdcbbbbbbbb
aaaaaaaaaabdccccccccccccccccdddfeeeeeeeegffgiikq feeddcccccccebbbbbbbbb
aaaaaaaaaabbccccccccccccccccccdddddegeeeegffgho p nheeddcccccchfbbbbbbbbb
aaaaaaaaaabbbddcccccccccccccccccdddddeeeeeefhm l ki jlnjeddcccccccdbbbbbbbbbb
aaaaaaaaaaabbccecccccccccccccccccdddddddfeeefir jii npm k ohgggineedcccccccdbbbbbbbbbbb
aaaaaaaaaaabbbccdddccccccccccccccccddddddddeeefggggggiik mjhhgfffffedddcccccccbbbbbbbbbbbb
aaaaaaaaaaaabbbcccedfcccccccccccccccdddddddddeegffffgghp hgffgeeeedddccccccccbbbbbbbbbbbb
aaaaaaaaaaaabbbbccccdddcccccccccccccccgdddddddddeegffgil ggfeeeeddddcccccccbbbbbbbbbbbbbb
aaaaaaaaaaaaabbbbbccccdddccccccccccccccfeddddddddeeeefgi l nkqgeeegeddddcccccccbbbbbbbbbbbbbbb
aaaaaaaaaaaaabbbbbbcccccdedccccccccccccccdedddddddeeeeeghik khhfeefdddddeccccccbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaabbbbbbccccccdddcccccccccccccddedddddddeeefigil jggfedddddddcccccbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaabbbbbbbcccccccdccccccccccccccdefdddddeeeffhlliimfdddddedccccccbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaabbbbbbbccccccdddccccccccccccccdddddddeeefg jggheddddedccccccbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaabbbbbbbbbccccccdddccccccccccccccdedddddefgiffeeddddeccccccbbbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaabbbbbbbbbbecccccdeeccccccccccccccceddddeffegddddgcccccbbbbbbbbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaaabbbbbbbbbbbbcccccdddcccccccccccccccccddddddddccccccbbbbbbbbbbbbbbbbbbbbbbbbbbc
aaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbccccddeccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbed
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbccceddcccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccd
aaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbdcccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbecccc
aaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccdebb
aaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbdfccbbb
aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcgdccbbbb
</pre>
=={{header|C sharp|C#}}==
<
using System.Drawing;
using System.Drawing.Imaging;
Line 2,772 ⟶ 4,399:
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,814 ⟶ 4,441:
}
}</
Note this code has not been executed.
Line 2,821 ⟶ 4,448:
<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 2,831 ⟶ 4,458:
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 2,892 ⟶ 4,519:
}
}
}</
=={{header|Cixl}}==
Displays a zooming Mandelbrot using ANSI graphics.
<
use: cx;
Line 2,967 ⟶ 4,594:
#out show-cursor
normal-mode
</syntaxhighlight>
=={{header|Clojure}}==
Inspired by the Ruby and Perl below
<syntaxhighlight lang="lisp">(defn complex-add
[[a0 b0] [a1 b1]]
[(+ a0 a1) (+ b0 b1)])
(defn complex-square
[[a b]]
[(- (* a a) (* b b)) (* 2 a b)])
(defn complex-abs
[[a b]]
(Math/sqrt (+ (* a a) (* b b))))
(defn f
[z c]
(complex-add z (complex-square c)))
(defn mandelbrot?
[z]
(> 2 (complex-abs (nth (iterate (partial f z) [0 0]) 20))))
(doseq [y (range 1 -1 -0.05)]
(doseq [x (range -2 0.5 0.0315)]
(print (if (mandelbrot? [(double x) (double y)]) "*" " ")))
(println ""))
</syntaxhighlight>
{{out}}
harold@freeside:~/src/mandelbrot$ clj -M mandelbrot.clj
*
* *** *
********
*********
******
** ** ************ *
*** ******************* * *
*****************************
****************************
********************************
********************************
************************************ *
* * ***********************************
*********** ***********************************
************ **************************************
************** ************************************
****************************************************
*******************************************************
************************************************************************
*******************************************************
****************************************************
************** ************************************
************ **************************************
*********** ***********************************
* * ***********************************
************************************ *
********************************
********************************
****************************
*****************************
*** ******************* * *
** ** ************ *
******
*********
********
* *** *
*
=={{header|COBOL}}==
EBCDIC art.
<
PROGRAM-ID. MANDELBROT-SET-PROGRAM.
DATA DIVISION.
Line 3,046 ⟶ 4,721:
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,075 ⟶ 4,750:
=={{header|Common Lisp}}==
<
(:use #:cl))
Line 3,119 ⟶ 4,794:
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,157 ⟶ 4,832:
print_nl();
cy := cy + dy;
end loop;</
{{out}}
<pre>!!!!!!!!!!!!!!!"""""""""""""####################################""""""""""""""""
Line 3,184 ⟶ 4,859:
!!!!!!!!!!!!!"""""""""#######################$$$$$$%%'3(%%%$$$$$######""""""""""
!!!!!!!!!!!!!!!""""""""""""#####################################""""""""""""""""</pre>
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">define max = 15, w = 640, h = 480
define py = 0, px = 0, sx = 0, sy = 0
define xx = 0, xy = 0
bgcolor 0, 0, 0
cls graphics
fill on
do
let px = 0
do
let sy = (py - h / 2) / 150
let sx = (px - w / 2) / 150
let i = 0
let x = 0
let y = 0
let xy = x * x + y * y
do
let xx = x * x - y * y + sx + .1
let y = 2 * x * y + sy
let x = xx
let i = i + 1
loop i < max and xy < 4
wait
fgcolor 220 + i * x, 220 + i * y, 230 + i * xy
rect px, py, 4, 4
let px = px + 4
loop px < w
let py = py + 4
loop py < h</syntaxhighlight>
=={{header|D}}==
===Textual Version===
This uses <code>std.complex</code> because D built-in complex numbers are deprecated.
<
import std.stdio, std.complex;
Line 3,199 ⟶ 4,922:
writeln;
}
}</
{{out}}
<pre>.......................................................................................
Line 3,253 ⟶ 4,976:
===More Functional Textual Version===
The output is similar.
<
import std.stdio, std.complex, std.range, std.algorithm;
Line 3,260 ⟶ 4,983:
.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,290 ⟶ 5,013:
}
while (true) { flip; events; }
}</
=={{header|Dart}}==
Implementation in Google Dart works on http://try.dartlang.org/ (as of 10/18/2011) since the language is very new, it may break in the future.
The implementation uses a incomplete Complex class supporting operator overloading.
<syntaxhighlight lang="dart">class Complex {
double _r,_i;
Line 3,330 ⟶ 5,053:
print(line);
}
}</
=={{header|Dc}}==
===ASCII output===
{{works with|GNU
{{works with|OpenBSD
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,407 ⟶ 5,130:
l2 x # loop
] s2
l2 x</
{{out}}
<pre>
Line 3,439 ⟶ 5,162:
===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,475 ⟶ 5,198:
l2 x
] s2
l2 x</
Line 3,482 ⟶ 5,205:
=={{header|DWScript}}==
{{trans|D}}
<
var x, y, i : Integer;
Line 3,498 ⟶ 5,221:
end;
PrintLn('');
end;</
=={{header|EasyLang}}==
[https://easylang.
<syntaxhighlight lang="easylang">
# Mandelbrot
#
res = 4
#
# better but slower:
# res = 8
# maxiter = 300
#
#
mid = res *
center_y = mid
scale = mid
#
background 000
textsize 2
#
fastfunc iter cx cy maxiter .
while xx + yy < 4 and it < maxiter
y = 2 * x * y + cy
x =
.
return it
.
proc draw . .
clear
for scr_y = 0 to 2 * mid - 1
cy = (scr_y - center_y) / scale
for scr_x = 0 to 2 * mid - 1
cx = (scr_x - center_x) / scale
it = iter cx cy maxiter
if it < maxiter
color3 it / 20 it / 100 it / 150
move scr_x / res scr_y / res
rect 1 / res 1 / res
.
.
.
color 990
move 1 1
text "Short press to zoom in, long to zoom out"
.
on mouse_down
time0 = systime
.
on mouse_up
center_x += mid - mouse_x * res
center_y += mid - mouse_y * res
if systime - time0 < 0.3
center_x -= mid - center_x
center_y -= mid - center_y
scale *= 2
else
center_x += (mid - center_x) * 3 / 4
center_y += (mid - center_y) * 3 / 4
scale /= 4
.
draw
.
draw
</syntaxhighlight>
=={{header|eC}}==
Line 3,531 ⟶ 5,300:
Drawing code:
<
{
int x, y;
Line 3,581 ⟶ 5,350:
}
}
}</
Interactive class with Rubberband Zoom:
<
{
caption = $"Mandelbrot";
Line 3,717 ⟶ 5,486:
}
Mandelbrot mandelbrotForm {};</
=={{header|EchoLisp}}==
<
(lib 'math) ;; fractal function
(lib 'plot)
Line 3,732 ⟶ 5,501:
;; result here [http://www.echolalie.org/echolisp/help.html#fractal]
</syntaxhighlight>
=={{header|Elixir}}==
<
def set do
xsize = 59
Line 3,763 ⟶ 5,532:
end
Mandelbrot.set</
{{out}}
Line 3,793 ⟶ 5,562:
=={{header|Emacs Lisp}}==
===Text mode===
<
(setq mandel-size (cons 76 34))
Line 3,834 ⟶ 5,603:
(insert(format "%s" (mandel-iter (mandel-pos x y))))))))
(mandel)</
{{output}}
<pre>----------------------------------------------------------------------------
Line 3,873 ⟶ 5,642:
===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 3,926 ⟶ 5,695:
(insert-image (string-to-image all)))
(mandel-pic)</
=={{header|Erlang}}==
Line 3,937 ⟶ 5,706:
[https://github.com/ghulette/mandelbrot-erlang Geoff Hulette's GitHub repository] provides two alternative implementations which are very interesting.
<
-module(mandelbrot).
Line 3,988 ⟶ 5,757:
% **************************************************
</syntaxhighlight>
Output:
Line 4,037 ⟶ 5,806:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MANDELBROT
Line 4,074 ⟶ 5,843:
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,138 ⟶ 5,907:
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,155 ⟶ 5,924:
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,195 ⟶ 5,964:
''' Graphics display '''
<
open System.Drawing
open System.Windows.Forms
Line 4,216 ⟶ 5,985:
showGraphic toColor 640 480 5000 ((-2.0,1.0),(-1.0,1.0))
</syntaxhighlight>
=={{header|Factor}}==
<syntaxhighlight lang="factor">
! with ("::") or without (":") generalizations:
! : [a..b] ( steps a b -- a..b ) 2dup swap - 4 nrot 1 - / <range> ;
Line 4,253 ⟶ 6,022:
70 25 1000 mandel
</syntaxhighlight>
{{out}}
Line 4,288 ⟶ 6,057:
=={{header|Fennel}}==
<syntaxhighlight lang="fennel">
#!/usr/bin/env fennel
Line 4,319 ⟶ 6,088:
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,346 ⟶ 6,115:
5.1 S T=MIT; T "*"; R
6.1 T " "; R</
{{output}}
<pre>
Line 4,377 ⟶ 6,146:
=={{header|Forth}}==
This uses [[grayscale image]] utilities.
<
: mandel ( gmp F: imin imax rmin rmax -- )
Line 4,400 ⟶ 6,169:
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,446 ⟶ 6,215:
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,505 ⟶ 6,274:
close (10)
end program mandelbrot</
=={{header|Frink}}==
This draws a graphical Mandelbrot set using Frink's built-in graphics and complex arithmetic.
<syntaxhighlight lang="frink">
// Maximum levels for each pixel.
levels = 60
Line 4,544 ⟶ 6,313:
g.show[]
</syntaxhighlight>
=={{header|Furor}}==
<syntaxhighlight lang="furor">
###sysinclude X.uh
$ff0000 sto szin
Line 4,593 ⟶ 6,362:
{ „XRES” }
{ „myscreen” }
</syntaxhighlight>
Line 4,600 ⟶ 6,369:
Computes escapes for each pixel, but not the colour.
<syntaxhighlight lang="futhark">
default(f32)
Line 4,641 ⟶ 6,410:
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}}==
<syntaxhighlight lang="futurebasic">
_xmin = -8601
_xmax = 2867
_ymin = -4915
_ymax = 4915
_maxiter = 32
_dx = ( _xmax - _xmin ) / 79
_dy = ( _ymax - _ymin ) / 24
void local fn MandelbrotSet
printf @"\n"
SInt32 cy = _ymin
while ( cy <= _ymax )
SInt32 cx = _xmin
while ( cx <= _xmax )
SInt32 x = 0
SInt32 y = 0
SInt32 x2 = 0
SInt32 y2 = 0
SInt32 iter = 0
while ( iter < _maxiter )
if ( x2 + y2 > 16384 ) then break
y = ( ( x * y ) >> 11 ) + (SInt32)cy
x = x2 - y2 + (SInt32)cx
x2 = ( x * x ) >> 12
y2 = ( y * y ) >> 12
iter++
wend
print fn StringWithFormat( @"%3c", iter + 32 );
cx += _dx
wend
printf @"\n"
cy += _dy
wend
end fn
window 1, @"Mandelbrot Set", ( 0, 0, 820, 650 )
WindowSetBackgroundColor( 1, fn ColorBlack )
text @"Impact", 10.0, fn ColorWithRGB( 1.000, 0.800, 0.000, 1.0 )
fn MandelbrotSet
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
!!!!!!!!!!!!!!!"""""""""""""####################################""""""""""""""""
!!!!!!!!!!!!!"""""""""#######################$$$$$$$%'+)%%%$$$$$#####"""""""""""
!!!!!!!!!!!"""""""#######################$$$$$$$$%%%&&(+,)++&%$$$$$$######""""""
!!!!!!!!!"""""#######################$$$$$$$$$$%%%%&')*5:/+('&%%$$$$$$#######"""
!!!!!!!!""""#####################$$$$$$$$$$%%%&&&''),@@@@@@@,'&%%%%%$$$$########
!!!!!!!"""####################$$$$$$$$%%%&'())((())*,@@@@@@/+))('&&&&)'%$$######
!!!!!!""###################$$$$$%%%%%%&&&'+.@@=/<@@@@@@@@@@@@@@@/++@..93%%$#####
!!!!!"################$$$%%%%%%%%%%&&&&'),+2@@@@@@@@@@@@@@@@@@@@@@@@@1(&&%$$####
!!!!"##########$$$$$%%&(-(''''''''''''(*,5@@@@@@@@@@@@@@@@@@@@@@@@@@@@+)-&%$$###
!!!!####$$$$$$$$%%%%%&'(*-@1.+.@-4+))**@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@4-(&%$$$##
!!!!#$$$$$$$$$%%%%%%'''++.6@@@@@@@@@8/0@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@3(%%$$$$#
!!!#$$$$$$$%&&&&''()/-5.5@@@@@@@@@@@@@>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@?'&%%$$$$#
!!!(**+/+<523/80/46@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@4+)'&&%%$$$$#
!!!#$$$$$$$%&&&&''().-2.@@@@@@@@@@@@@@?@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'&%%$$$$#
!!!!#$$$$$$$$$%%%%%&'''/,.7@@@@@@@@@;/0@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@0'%%$$$$#
!!!!####$$$$$$$$%%%%%&'(*-:2.,/?-5+))**@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@4+(&%$$$##
!!!!"##########$$$$$%%&(-(''''(''''''((*,4@@@@@@@@@@@@@@@@@@@@@@@@@@@4+).&%$$###
!!!!!"################$$$%%%%%%%%%%&&&&')<,4@@@@@@@@@@@@@@@@@@@@@@@@@/('&%%$####
!!!!!!""##################$$$$$$%%%%%%&&&'*.@@@0@@@@@@@@@@@@@@@@1,,@//9)%%$#####
!!!!!!!"""####################$$$$$$$$%%%&(())((()**-@@@@@@/+)))'&&&')'%$$######
!!!!!!!!""""#####################$$$$$$$$$$%%%&&&''(,@@@@@@@+'&&%%%%%$$$########
!!!!!!!!!"""""#######################$$$$$$$$$$%%%%&')*7@0+('&%%%$$$$$#######"""
!!!!!!!!!!!"""""""######################$$$$$$$$$%%%&&(+-).*&%$$$$$$######""""""
!!!!!!!!!!!!!"""""""""#######################$$$$$$%%'3(%%%$$$$$######""""""""""
!!!!!!!!!!!!!!!""""""""""""#####################################"""""""""""""""
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Mandelbrot_set}}
'''Solution'''
We need first to generate a color palette, this is, a list of colors:
[[File:Fōrmulæ - Julia set 01.png]]
[[File:Fōrmulæ - Julia set 02.png]]
[[File:Fōrmulæ - Julia set 03.png]]
The following function draw the Mandelbrot set:
[[File:Fōrmulæ - Mandelbrot set 01.png]]
'''Test Case 1. Grayscale palette'''
[[File:Fōrmulæ - Mandelbrot set 02.png]]
[[File:Fōrmulæ - Mandelbrot set 03.png]]
'''Test case 2. Black & white palette'''
[[File:Fōrmulæ - Mandelbrot set 04.png]]
[[File:Fōrmulæ - Mandelbrot set 05.png]]
=={{header|GLSL}}==
Uses smooth coloring.
<
const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
Line 4,704 ⟶ 6,573:
}
</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,719 ⟶ 6,588:
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,726 ⟶ 6,595:
;Text
Prints an 80-char by 41-line depiction.
<
import "fmt"
Line 4,749 ⟶ 6,618:
fmt.Println("")
}
}</
;Graphical
[[File:GoMandelbrot.png|thumb|right|.png image]]
<
import (
Line 4,811 ⟶ 6,680:
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 4,863 ⟶ 6,732:
=={{header|Hare}}==
{{trans|D}}
<
use math;
Line 4,892 ⟶ 6,761:
fn abs(z: complex) f64 = {
return math::sqrtf64(z.re*z.re + z.im*z.im);
};</
{{out}}
<pre>
Line 4,947 ⟶ 6,816:
=={{header|Haskell}}==
{{trans|Ruby}}
<
import Data.Complex (Complex ((:+)), magnitude)
mandelbrot :: RealFloat a => Complex a -> Complex a
mandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50
Line 4,960 ⟶ 6,827:
putStrLn
[ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y)))
| x <- [-2, -1.9685 .. 0.5
| y <- [1, 0.95 .. -1]
]</syntaxhighlight>
{{Out}}
<pre>
Line 5,005 ⟶ 6,870:
'''haskell one-liners :'''
<
-- first attempt
Line 5,020 ⟶ 6,885:
-- 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,055 ⟶ 6,920:
)
[".", "\'", ":", "!", "|", "}", "#", " "]
)</
{{Out}}
<pre> #
Line 5,148 ⟶ 7,013:
and a legible variant of the last of the "one-liner" contributions above:
<
main =
mapM_
Line 5,167 ⟶ 7,032:
else ' '
]
]</
=={{header|Haxe}}==
This version compiles for flash version 9 or greater.
The compilation command is
<
<
{
inline static var MAX_ITER = 255;
Line 5,222 ⟶ 7,087:
image.setPixel(x, y, color);
}
}</
=={{header|Huginn}}==
<
exec huginn -E "${0}" "${@}"
#! huginn
Line 5,279 ⟶ 7,144:
columns -= 1;
return ( ( lines, columns ) );
}</
{{out}}
Line 5,328 ⟶ 7,193:
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main()
Line 5,373 ⟶ 7,238:
procedure cAbs(x)
return sqrt(x.r*x.r+x.i*x.i)
end</
{{libheader|Icon Programming Library}}
Line 5,384 ⟶ 7,249:
(free implementation: GDL - GNU Data Language
http://gnudatalanguage.sourceforge.net)
<syntaxhighlight lang="idl">
PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations
Line 5,431 ⟶ 7,296:
END
</syntaxhighlight>
from the command line:
<syntaxhighlight lang="idl">
GDL>.run mandelbrot
</syntaxhighlight>
or
<syntaxhighlight lang="idl">
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,629 ⟶ 7,494:
[ 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.
[[File:Mandelbrot-Inform7.png]]
=={{Header|Insitux}}==
<syntaxhighlight lang="insitux">
(function mandelbrot width height depth
(.. str
(for yy (range height)
xx (range width)
(let c_re (/ (* (- xx (/ width 2)) 4) width)
c_im (/ (* (- yy (/ height 2)) 4) width)
x 0 y 0 i 0)
(while (and (<= (+ (** x) (** y)) 4)
(< i depth))
(let x2 (+ c_re (- (** x) (** y)))
y (+ c_im (* 2 x y))
x x2
i (inc i)))
(strn ((zero? xx) "\n") (i "ABCDEFGHIJ ")))))
(mandelbrot 48 24 10)
</syntaxhighlight>
{{out}}
<pre>
BBBBCCCDDDDDDDDDEEEEFGJJ EEEDDCCCCCCCCCCCCCCCBBB
BBBCCDDDDDDDDDDEEEEFFH HFEEEDDDCCCCCCCCCCCCCCBB
BBBCDDDDDDDDDDEEEEFFH GFFEEDDDCCCCCCCCCCCCCBB
BBCCDDDDDDDDDEEEEGGHI HGFFEDDDCCCCCCCCCCCCCCB
BBCDDDDDDDDEEEEFG HIGEDDDCCCCCCCCCCCCCB
BBDDDDDDDDEEFFFGH IEDDDDCCCCCCCCCCCCB
BCDDDDDDEEFFFFGG GFEDDDCCCCCCCCCCCCC
BDDDDDEEFJGGGHHI IFEDDDDCCCCCCCCCCCC
BDDEEEEFG J JI GEDDDDCCCCCCCCCCCC
BDEEEFFFHJ FEDDDDCCCCCCCCCCCC
BEEEFFFIJ FEEDDDCCCCCCCCCCCC
BEEFGGH HFEEDDDCCCCCCCCCCCC
JGFEEDDDDCCCCCCCCCCC
BEEFGGH HFEEDDDCCCCCCCCCCCC
BEEEFFFIJ FEEDDDCCCCCCCCCCCC
BDEEEFFFHJ FEDDDDCCCCCCCCCCCC
BDDEEEEFG J JI GEDDDDCCCCCCCCCCCC
BDDDDDEEFJGGGHHI IFEDDDDCCCCCCCCCCCC
BCDDDDDDEEFFFFGG GFEDDDCCCCCCCCCCCCC
BBDDDDDDDDEEFFFGH IEDDDDCCCCCCCCCCCCB
BBCDDDDDDDDEEEEFG HIGEDDDCCCCCCCCCCCCCB
BBCCDDDDDDDDDEEEEGGHI HGFFEDDDCCCCCCCCCCCCCCB
BBBCDDDDDDDDDDEEEEFFH GFFEEDDDCCCCCCCCCCCCCBB
BBBCCDDDDDDDDDDEEEEFFH HFEEEDDDCCCCCCCCCCCCCCBB
</pre>
=={{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):
<syntaxhighlight lang="j"> viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.1 NB. Complex interval and resolution</syntaxhighlight>
=={{header|Java}}==
{{libheader|Swing}} {{libheader|AWT}}
<
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
Line 5,696 ⟶ 7,608:
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 5,992 ⟶ 7,904:
;
}
}</
=={{header|JavaScript}}==
Line 6,001 ⟶ 7,913:
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,069 ⟶ 7,981:
document.body.insertBefore(canvas, document.body.childNodes[0]);
mandelbrot(canvas, -2, 1, -1, 1, 1000);</
{{out}} with default parameters:
Line 6,079 ⟶ 7,991:
one for instance with the [https://mbebenita.github.io/WasmExplorer/ WebAssembly explorer]
<
fetch("./mandelIter.wasm")
.then(res => {
Line 6,100 ⟶ 8,012:
mandelbrot(canvas, -2, 1, -1, 1, 1000);
// ...
}</
=={{header|jq}}==
Line 6,110 ⟶ 8,022:
'''Preliminaries'''
<
def svg(id; width; height):
"<svg width='\(width // "100%")' height='\(height // "100%") '
Line 6,124 ⟶ 8,036:
def u: if condition then . else (next|u) end;
u;
</
def Mandeliter( cx; cy; maxiter ):
# [i, x, y, x^2+y^2]
Line 6,164 ⟶ 8,076:
svg("mandelbrot"; "100%"; "100%"),
pixies,
"</svg>";</
'''Example''':
<
'''Execution:'''
Line 6,178 ⟶ 8,090:
Generates an ASCII representation:
<
z = 0
for i=1:50
Line 6,191 ⟶ 8,103:
end
println()
end</
This generates a PNG image file:
<
@inline function hsv2rgb(h, s, v)
Line 6,233 ⟶ 8,145:
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. See Javier Barrallo & Damien M. Jones: Coloring Algorithms for Dynamical Systems in the Complex Plane ([http://www.mi.sanu.ac.rs/vismath/javier/b3.htm ''II. Distance Estimators'']).
<
gr(aspect_ratio=:equal, legend=false, axis=false, ticks=false, dpi=100)
Line 6,263 ⟶ 8,175:
gif(animation, "Mandelbrot_animation.gif", fps=2)
gif(smoothing, "Mandelbrot_smoothing.gif", fps=2)</
===
'''Normalization, Distance Estimation and Boundary Detection'''
This is a translation of the corresponding Python section: see there for more explanations. The ''e^(-|z|)-smoothing'', ''normalized iteration count'' and ''exterior distance estimation'' algorithms are used. Partial antialiasing is used for boundary detection.
<syntaxhighlight lang="julia">using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
Line 6,276 ⟶ 8,191:
y = range(0, 2 * h / d, length=h+1)
A, B = collect(x) .- 1
C =
Z, dZ = zero(C), zero(C)
for k in 1:n
M =
S[M], T[M] = S[M] .+ exp.(.- abs.(Z[M])), T[M] .+ 1
Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1
end
heatmap(S .^ 0.1, c=:
savefig("Mandelbrot_set_1.png")
N = abs.(Z) .>= r # normalized iteration count
T[N] = T[N] .- log2.(log.(abs.(Z[N])) ./ log(r))
heatmap(T .^ 0.1, c=:
savefig("Mandelbrot_set_2.png")
N = abs.(Z) .> 2 # exterior distance estimation
D[N] =
heatmap(D .^ 0.1, c=:
savefig("Mandelbrot_set_3.png")
N, thickness = D .> 0, 0.01 # boundary detection
D[N] = max.(1 .- D[N] ./ thickness, 0)
heatmap(D .^ 2.0, c=:binary)
savefig("Mandelbrot_set_4.png")</syntaxhighlight>
'''Normal Map Effect and Stripe Average Coloring'''
The Mandelbrot set is represented using Normal Maps and Stripe Average Coloring by Jussi Härkönen (cf. Arnaud Chéritat: [https://www.math.univ-toulouse.fr/~cheritat/wiki-draw/index.php/Mandelbrot_set#Normal_map_effect ''Normal map effect'']). See also the picture in section [https://www.math.univ-toulouse.fr/~cheritat/wiki-draw/index.php/Mandelbrot_set#Mixing_it_all ''Mixing it all''] and [https://www.shadertoy.com/view/wtscDX Julia Stripes] on Shadertoy. To get a stripe pattern similar to that of Arnaud Chéritat, one can increase the ''density'' of the stripes, use ''cos'' instead of ''sin'', and set the colormap to ''binary''.
<syntaxhighlight lang="julia">using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
d, h =
n, r =
direction, height = 45.0, 1.5 # direction and height of the light
density, intensity = 4.0, 0.5 # density and intensity of the stripes
x = range(0, 2, length=d+1)
y = range(0, 2 * h / d, length=h+1)
A, B = collect(x) .
C = (2.
Z, dZ, ddZ = zero(C), zero(C), zero(C)
D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C))
for k in 1:n
M =
Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M])
end
N = abs.(Z) .>=
U, V = Z[N] ./ dZ[N], 1 .+ (log2.(log.(abs.(Z[N])) ./ log(r)) .* (P .- Q) .+ Q) .* intensity
U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector
D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ V .* height) ./ (1 + height), 0)
heatmap(D
savefig("
N = abs.(Z) .> 2 # advanced normal map effect using higher derivatives (distance estimation)
U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector
D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0)
heatmap(D .^ 1.0, c=:afmhot)
savefig("Mandelbrot_normal_map_2.png")</syntaxhighlight>
'''Mercator Mandelbrot Maps and Zoom Images'''
A small change in the code above creates Mercator maps and zoom images of the Mandelbrot set. See also the album [https://www.flickr.com/photos/arenamontanus/albums/72157615740829949 Mercator Mandelbrot Maps] by Anders Sandberg and [https://commons.wikimedia.org/wiki/File:Mandelbrot_sequence_new.gif ''Mandelbrot sequence new''] on Wikimedia for a zoom animation to the given coordinates.
<syntaxhighlight lang="julia">using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
d, h = 200, 1200 # pixel density (= image width) and image height
n, r = 8000, 10000 # number of iterations and escape radius (r > 2)
a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html
b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800
x = range
y = range
A, B = collect(x) .* pi
C =
Z, dZ = zero(C), zero(C)
D = zeros(size(C))
for k in 1:n
M =
Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1
end
N = abs.(Z) .> 2 # exterior distance estimation
D[N] =
heatmap(D' .^ 0.05, c=:nipy_spectral)
savefig("
X, Y = real(C), imag(C) # zoom images (adjust circle size 50 and zoom level 20 as needed)
R, c, z = 50 * (2 / d) * pi .* exp.(.- B), min(d, h) + 1, max(0, h - d) ÷ 20
gr(c=:nipy_spectral, axis=true, ticks=true, legend=false, markerstrokewidth=0)
p1 = scatter(X[1z+1:1z+c,1:d], Y[1z+1:1z+c,1:d], markersize=R[1:c].^.5, marker_z=D[1z+1:1z+c,1:d].^.5)
p2 = scatter(X[2z+1:2z+c,1:d], Y[2z+1:2z+c,1:d], markersize=R[1:c].^.5, marker_z=D[2z+1:2z+c,1:d].^.4)
p3 = scatter(X[3z+1:3z+c,1:d], Y[3z+1:3z+c,1:d], markersize=R[1:c].^.5, marker_z=D[3z+1:3z+c,1:d].^.3)
p4 = scatter(X[4z+1:4z+c,1:d], Y[4z+1:4z+c,1:d], markersize=R[1:c].^.5, marker_z=D[4z+1:4z+c,1:d].^.2)
plot(p1, p2, p3, p4, layout=(2, 2))
savefig("Mercator_Mandelbrot_zoom.png")</syntaxhighlight>
'''Perturbation Theory and Deep Mercator Maps'''
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. Rebasing is used to reduce glitches. See [https://fractalforums.org/fractal-mathematics-and-new-theories/28/another-solution-to-perturbation-glitches/4360 Another solution to perturbation glitches] (Fractalforums) for details. See also the image [https://www.flickr.com/photos/arenamontanus/3430921497/in/album-72157615740829949/ Deeper Mercator Mandelbrot] by Anders Sandberg.
<syntaxhighlight lang="julia">using Plots
gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)
setprecision(BigFloat, 256) # set precision to 256 bits (default)
setrounding(BigFloat, RoundNearest) # set rounding mode (default)
d, h = 50, 1000 # pixel density (= image width) and image height
n, r = 80000, 100000 # number of iterations and escape radius (r > 2)
a = BigFloat("-1.256827152259138864846434197797294538253477389787308085590211144291")
b = BigFloat(".37933802890364143684096784819544060002129071484943239316486643285025")
S = zeros(Complex{Float64}, n+1)
let c = a + b * im, z = zero(c)
for k in 1:n+1
S[k] = z
if abs2(z) < abs2(r)
z = z ^ 2 + c
else
println("The reference sequence diverges within $(k-1) iterations.")
break
end
end
end
x = range(0, 2, length=d+1)
y = range(0, 2 * h / d, length=h+1)
A, B = collect(x) .* pi, collect(y) .* pi
C = 8.0 .* exp.((A' .+ B .* im) .* im)
E, Z, dZ = zero(C), zero(C), zero(C)
D, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C))
for k in 1:n
M, R =
Z[M], dZ[M] = S[I[M]] .+ E[M], 2 .* Z[M] .* dZ[M] .+ 1
end
N = abs.(Z) .> 2 # exterior distance estimation
D[N] =
heatmap(D' .^ 0.
savefig("
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.awt.Graphics
Line 6,454 ⟶ 8,407:
fun main(args: Array<String>) {
Mandelbrot().isVisible = true
}</
=={{header|LabVIEW}}==
Line 6,462 ⟶ 8,415:
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">
: d2c(*,*) 2 compress 'c dress ; # Make a complex number.
Line 6,476 ⟶ 8,429:
iterate abs int 5 min 'print_line apply # Compute & print
</syntaxhighlight>
=={{header|Lambdatalk}}==
Line 6,485 ⟶ 8,438:
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.
<syntaxhighlight lang="scheme">
{def mandel
Line 6,517 ⟶ 8,470:
{S.serie 0 40}} // y resolution
</syntaxhighlight>
<pre>
Line 6,564 ⟶ 8,517:
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
define mandelbrotBailout => 16
define mandelbrotMaxIterations => 1000
Line 6,616 ⟶ 8,569:
mandelbrotTest
</syntaxhighlight>
{{out}}
<small>
Line 6,701 ⟶ 8,654:
=={{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 6,762 ⟶ 8,715:
}}
}
}</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
cs setpensize [1 1]
make "inc :side/:size
Line 6,800 ⟶ 8,753:
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 6,874 ⟶ 8,827:
love.graphics.draw( canvas )
end
</syntaxhighlight>
===ASCII===
<
local charmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "@" }
for y = -1.3, 1.3, 0.1 do
Line 6,888 ⟶ 8,841:
end
print()
end</
{{out}}
<pre>...............::::::::::::::::::---------------::::::::::::::::::::::::::::::::
Line 6,917 ⟶ 8,870:
.............:::::::::::---------------------------------:::::::::::::::::::::::
...............::::::::::::::::::---------------::::::::::::::::::::::::::::::::</pre>
===ASCII (obfuscated)===
Produces an 80x25 ASCII Mandelbrot set, using only two lines of code. The result isn't very high quality because there's only so many iterations you can cram into two lines of 80 columns. And this code cheats, because it starts the iteration count at -15 instead of 0, to avoid the need for an excessively long character lookup table.
<syntaxhighlight lang="lua">for y=-12,12 do l=""for x=-2,1,3/80 do a,b,n=0,0,-15 while n<9 and a*a+b*b<1e12
do a,b,n=a*a-b*b+x,2*a*b+y/8,n+1 end l=l..(".,:;=$%# "):sub(n,n)end print(l)end</syntaxhighlight>
{{out}}
<pre>............................................,,,,,,,,............................
.................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,...................
.........................,,,,,,,,,,,,,,,,,,,,,,::::,,,,,,,,,,,,,,,..............
...................,,,,,,,,,,,,,,,,,,,,,::::::;=$=;;::::::,,,,,,,,,,,,..........
..............,,,,,,,,,,,,,,,,,,,,:::::::::;;;==% :#=;;:::::,,,,,,,,,,,.......
.........,,,,,,,,,,,,,,,,,,,,:::::::::;;;;;==$%;; ,##==;;;::::::,,,,,,,,,.....
.....,,,,,,,,,,,,,,,,,:::::::::::;;;;====$$$%#: %$$===;;;;::::,,,,,,,,...
..,,,,,,,,,,,,,,::::::::::::;;;;;;==$ , .#% #=;:::,,,,,,,,,.
,,,,,,,,,,,,::::::;;;;;;;;;;=====$$#:. $=;;::::,,,,,,,,
,,,,,,,,:::::::;;;=%:%%%%%=%%%%%%# $ $;;:::,,,,,,,,
,,,,:::::::;;;;===$%#: ,.. :,=;;::::,,,,,,,
::::;;;;;;====$# ..# ;$=;;::::,,,,,,,
; %$=;;;::::,,,,,,,
::::;;;;;;====$# ..# ;$=;;::::,,,,,,,
,,,,:::::::;;;;===$%#: ,.. :,=;;::::,,,,,,,
,,,,,,,,:::::::;;;=%:%%%%%=%%%%%%# $ $;;:::,,,,,,,,
,,,,,,,,,,,,::::::;;;;;;;;;;=====$$#:. $=;;::::,,,,,,,,
..,,,,,,,,,,,,,,::::::::::::;;;;;;==$ , .#% #=;:::,,,,,,,,,.
.....,,,,,,,,,,,,,,,,,:::::::::::;;;;====$$$%#: %$$===;;;;::::,,,,,,,,...
.........,,,,,,,,,,,,,,,,,,,,:::::::::;;;;;==$%;; ,##==;;;::::::,,,,,,,,,.....
..............,,,,,,,,,,,,,,,,,,,,:::::::::;;;==% :#=;;:::::,,,,,,,,,,,.......
...................,,,,,,,,,,,,,,,,,,,,,::::::;=$=;;::::::,,,,,,,,,,,,..........
.........................,,,,,,,,,,,,,,,,,,,,,,::::,,,,,,,,,,,,,,,..............
.................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,...................
............................................,,,,,,,,............................</pre>
=={{header|M2000 Interpreter}}==
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).
<syntaxhighlight lang="m2000 interpreter">
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
Line 6,943 ⟶ 8,930:
if abs(Cy)<Ph2 Then Cy=0
For iX=0 to iXm Step PixelWidth {
Let Cx=CxMin+iX,Zx=0,Zy=0,Zx2=
For It=Iteration to 1 {Let Zy=2*Zx*Zy+Cy,Zx=Zx2-Zy2+Cx,Zx2=Zx**2,Zy2=Zy**2 :if Zx2+Zy2>ER2 Then exit
}
Line 6,961 ⟶ 8,948:
}
</syntaxhighlight>
Version 2 without Subroutine. Also there is a screen refresh every 2 seconds.
<syntaxhighlight lang="m2000 interpreter">
Module Mandelbrot(x=0&,y=0&,z=1&) {
If z<1 then z=1
Line 6,988 ⟶ 8,975:
move xp, yp
For iX=0 to iXm Step PixelWidth {
Let Cx=CxMin+iX,Zx=0,Zy=0,Zx2=
For It=Iteration to 1 {Let Zy=2*Zx*Zy+Cy,Zx=Zx2-Zy2+Cx,Zx2=Zx**2,Zy2=Zy**2 :if Zx2+Zy2>ER2 Then exit
}
Line 7,003 ⟶ 8,990:
Mandelbrot 250*twipsx,100*twipsy, array(i)
}
</syntaxhighlight>
=={{header|M4}}==
{{works with|GNU m4|1.4.19}}
{{works with|OpenBSD m4}}
{{works with|Heirloom Development Tools m4}}
The following m4 code is not optimized very well, but it works. It is actually output from [https://sourceforge.net/p/chemoelectric/rosettacode-contributions/ci/default/tree/vmc.dats a program I call '''vmc'''], which translates output from [[Compiler/code_generator|the code generator task]] to different languages. The Mandelbrot set algorithm from the test set for that task. The '''vmc''' program itself is written in [[ATS|ATS]], and the m4 it generates should run in any POSIX-compliant m4 (if not others as well). For very old m4 implementations, one might need to use an option such as <code>-S 1000</code> to set the stack size larger than the default.
There are two data structures employed:
* A FORTH-like data stack, an example of which would be <code>789:456:123:stack-bottom</code>
* A list of variables, such as <code>var0:123:var1:456:var2:789:</code>
There are macros to do calculations with the stack. There are also macros to <code>fetch</code> and <code>store</code> the values of variables, which are referenced by name.
One might enjoy even manually writing m4 code using such structures. However, the big mutual recursion that is the core of the program probably is not how one would write code manually.
(None of the above involves m4's notorious trickery with commas.)
<syntaxhighlight lang="m4">
divert(-1)
changecom
define(`newline',`
')
define(`leftquote',`[')
define(`rightquote',`]')
changequote(`[',`]')
define([print_char],
[ifelse(
$1,0,[*],
$1,1,[*],
$1,2,[*],
$1,3,[*],
$1,4,[*],
$1,5,[*],
$1,6,[*],
$1,7,[*],
$1,8,[*],
$1,9,[*],
$1,10,[newline],
$1,11,[*],
$1,12,[*],
$1,13,[*],
$1,14,[*],
$1,15,[*],
$1,16,[*],
$1,17,[*],
$1,18,[*],
$1,19,[*],
$1,20,[*],
$1,21,[*],
$1,22,[*],
$1,23,[*],
$1,24,[*],
$1,25,[*],
$1,26,[*],
$1,27,[*],
$1,28,[*],
$1,29,[*],
$1,30,[*],
$1,31,[*],
$1,32,[ ],
$1,33,[!],
$1,34,["],
$1,35,[#],
$1,36,[$],
$1,37,[%],
$1,38,[&],
$1,39,['],
$1,40,[(],
$1,41,[)],
$1,42,[*],
$1,43,[+],
$1,44,[,],
$1,45,[-],
$1,46,[.],
$1,47,[/],
$1,48,[0],
$1,49,[1],
$1,50,[2],
$1,51,[3],
$1,52,[4],
$1,53,[5],
$1,54,[6],
$1,55,[7],
$1,56,[8],
$1,57,[9],
$1,58,[:],
$1,59,[;],
$1,60,[<],
$1,61,[=],
$1,62,[>],
$1,63,[?],
$1,64,[@],
$1,65,[A],
$1,66,[B],
$1,67,[C],
$1,68,[D],
$1,69,[E],
$1,70,[F],
$1,71,[G],
$1,72,[H],
$1,73,[I],
$1,74,[J],
$1,75,[K],
$1,76,[L],
$1,77,[M],
$1,78,[N],
$1,79,[O],
$1,80,[P],
$1,81,[Q],
$1,82,[R],
$1,83,[S],
$1,84,[T],
$1,85,[U],
$1,86,[V],
$1,87,[W],
$1,88,[X],
$1,89,[Y],
$1,90,[Z],
$1,91,[changequote([`],['])leftquote`'changequote(`[',`]')],
$1,92,[\],
$1,93,[rightquote],
$1,94,[^],
$1,95,[_],
$1,96,[`],
$1,97,[a],
$1,98,[b],
$1,99,[c],
$1,100,[d],
$1,101,[e],
$1,102,[f],
$1,103,[g],
$1,104,[h],
$1,105,[i],
$1,106,[j],
$1,107,[k],
$1,108,[l],
$1,109,[m],
$1,110,[n],
$1,111,[o],
$1,112,[p],
$1,113,[q],
$1,114,[r],
$1,115,[s],
$1,116,[t],
$1,117,[u],
$1,118,[v],
$1,119,[w],
$1,120,[x],
$1,121,[y],
$1,122,[z],
$1,123,[{],
$1,124,[|],
$1,125,[}],
$1,126,[~],
[*])])
define([stack_1st],[substr([$1],0,index([$1],[:]))])
define([stack_2nd],[stack_1st(stack_drop([$1]))])
define([stack_drop],[substr([$1],eval(index([$1],[:]) [+ 1]))])
define([stack_drop2],[stack_drop(stack_drop([$1]))])
define([stack_not],[eval(stack_1st([$1]) [== 0]):stack_drop([$1])])
define([stack_neg],[eval([-] stack_1st([$1])):stack_drop([$1])])
define([stack_and],[eval(stack_2nd([$1] [!= 0]) [&&] stack_1st([$1] [!= 0])):stack_drop2([$1])])
define([stack_or],[eval(stack_2nd([$1] [!= 0]) [||] stack_1st([$1] [!= 0])):stack_drop2([$1])])
define([stack_lt],[eval(stack_2nd([$1]) [<] stack_1st([$1])):stack_drop2([$1])])
define([stack_le],[eval(stack_2nd([$1]) [<=] stack_1st([$1])):stack_drop2([$1])])
define([stack_gt],[eval(stack_2nd([$1]) [>] stack_1st([$1])):stack_drop2([$1])])
define([stack_ge],[eval(stack_2nd([$1]) [>=] stack_1st([$1])):stack_drop2([$1])])
define([stack_eq],[eval(stack_2nd([$1]) [==] stack_1st([$1])):stack_drop2([$1])])
define([stack_ne],[eval(stack_2nd([$1]) [!=] stack_1st([$1])):stack_drop2([$1])])
define([stack_add],[eval(stack_2nd([$1]) [+] stack_1st([$1])):stack_drop2([$1])])
define([stack_sub],[eval(stack_2nd([$1]) [-] stack_1st([$1])):stack_drop2([$1])])
define([stack_mul],[eval(stack_2nd([$1]) [*] stack_1st([$1])):stack_drop2([$1])])
define([stack_div],[eval(stack_2nd([$1]) [/] stack_1st([$1])):stack_drop2([$1])])
define([stack_mod],[eval(stack_2nd([$1]) [%] stack_1st([$1])):stack_drop2([$1])])
define([prtc_1st],[print_char(stack_1st([$1]))])
define([prti_1st],[stack_1st([$1])])
define([prts_1st],[print_string(stack_1st([$1]))])
define([store],[define([_tmp1],index([$2],[$1:]))[]substr([$2],0,_tmp1)[$1:$3]define([_tmp2],substr([$2],eval(_tmp1 + len([$1]) [+ 1])))substr(_tmp2,index(_tmp2,[:]))])
define([fetch],[define([_tmp],substr([$2],eval(index([$2],[$1:]) [+] len([$1]) [+ 1])))[]substr(_tmp,0,index(_tmp,[:]))])
define([initial_vars],[var0:0:var1:0:var2:0:var3:0:var4:0:var5:0:var6:0:var7:0:var8:0:var9:0:var10:0:var11:0:var12:0:var13:0:var14:0:])
define([kont0],[kont5([420:$1],[$2])])
define([kont5],[kont6(stack_neg([$1]),[$2])])
define([kont6],[kont11(stack_drop([$1]),store([var0],[$2],stack_1st([$1])))])
define([kont11],[kont16([300:$1],[$2])])
define([kont16],[kont21(stack_drop([$1]),store([var1],[$2],stack_1st([$1])))])
define([kont21],[kont26([300:$1],[$2])])
define([kont26],[kont31(stack_drop([$1]),store([var2],[$2],stack_1st([$1])))])
define([kont31],[kont36([300:$1],[$2])])
define([kont36],[kont37(stack_neg([$1]),[$2])])
define([kont37],[kont42(stack_drop([$1]),store([var3],[$2],stack_1st([$1])))])
define([kont42],[kont47([7:$1],[$2])])
define([kont47],[kont52(stack_drop([$1]),store([var4],[$2],stack_1st([$1])))])
define([kont52],[kont57([15:$1],[$2])])
define([kont57],[kont62(stack_drop([$1]),store([var5],[$2],stack_1st([$1])))])
define([kont62],[kont67([200:$1],[$2])])
define([kont67],[kont72(stack_drop([$1]),store([var6],[$2],stack_1st([$1])))])
define([kont72],[kont77(fetch([var2],[$2])[:$1],[$2])])
define([kont77],[kont82(stack_drop([$1]),store([var7],[$2],stack_1st([$1])))])
define([kont82],[kont87(fetch([var7],[$2])[:$1],[$2])])
define([kont87],[kont92(fetch([var3],[$2])[:$1],[$2])])
define([kont92],[kont93(stack_gt([$1]),[$2])])
define([kont93],[ifelse(eval(stack_1st([$1]) [== 0]),1,[kont423(stack_drop([$1]),[$2])],[kont98(stack_drop([$1]),[$2])])])
define([kont98],[kont103(fetch([var0],[$2])[:$1],[$2])])
define([kont103],[kont108(stack_drop([$1]),store([var8],[$2],stack_1st([$1])))])
define([kont108],[kont113(fetch([var8],[$2])[:$1],[$2])])
define([kont113],[kont118(fetch([var1],[$2])[:$1],[$2])])
define([kont118],[kont119(stack_lt([$1]),[$2])])
define([kont119],[ifelse(eval(stack_1st([$1]) [== 0]),1,[kont396(stack_drop([$1]),[$2])],[kont124(stack_drop([$1]),[$2])])])
define([kont124],[kont129([0:$1],[$2])])
define([kont129],[kont134(stack_drop([$1]),store([var9],[$2],stack_1st([$1])))])
define([kont134],[kont139([0:$1],[$2])])
define([kont139],[kont144(stack_drop([$1]),store([var10],[$2],stack_1st([$1])))])
define([kont144],[kont149([32:$1],[$2])])
define([kont149],[kont154(stack_drop([$1]),store([var11],[$2],stack_1st([$1])))])
define([kont154],[kont159([0:$1],[$2])])
define([kont159],[kont164(stack_drop([$1]),store([var12],[$2],stack_1st([$1])))])
define([kont164],[kont169(fetch([var12],[$2])[:$1],[$2])])
define([kont169],[kont174(fetch([var6],[$2])[:$1],[$2])])
define([kont174],[kont175(stack_lt([$1]),[$2])])
define([kont175],[ifelse(eval(stack_1st([$1]) [== 0]),1,[kont369(stack_drop([$1]),[$2])],[kont180(stack_drop([$1]),[$2])])])
define([kont180],[kont185(fetch([var10],[$2])[:$1],[$2])])
define([kont185],[kont190(fetch([var10],[$2])[:$1],[$2])])
define([kont190],[kont191(stack_mul([$1]),[$2])])
define([kont191],[kont196([200:$1],[$2])])
define([kont196],[kont197(stack_div([$1]),[$2])])
define([kont197],[kont202(stack_drop([$1]),store([var13],[$2],stack_1st([$1])))])
define([kont202],[kont207(fetch([var9],[$2])[:$1],[$2])])
define([kont207],[kont212(fetch([var9],[$2])[:$1],[$2])])
define([kont212],[kont213(stack_mul([$1]),[$2])])
define([kont213],[kont218([200:$1],[$2])])
define([kont218],[kont219(stack_div([$1]),[$2])])
define([kont219],[kont224(stack_drop([$1]),store([var14],[$2],stack_1st([$1])))])
define([kont224],[kont229(fetch([var13],[$2])[:$1],[$2])])
define([kont229],[kont234(fetch([var14],[$2])[:$1],[$2])])
define([kont234],[kont235(stack_add([$1]),[$2])])
define([kont235],[kont240([800:$1],[$2])])
define([kont240],[kont241(stack_gt([$1]),[$2])])
define([kont241],[ifelse(eval(stack_1st([$1]) [== 0]),1,[kont298(stack_drop([$1]),[$2])],[kont246(stack_drop([$1]),[$2])])])
define([kont246],[kont251([48:$1],[$2])])
define([kont251],[kont256(fetch([var12],[$2])[:$1],[$2])])
define([kont256],[kont257(stack_add([$1]),[$2])])
define([kont257],[kont262(stack_drop([$1]),store([var11],[$2],stack_1st([$1])))])
define([kont262],[kont267(fetch([var12],[$2])[:$1],[$2])])
define([kont267],[kont272([9:$1],[$2])])
define([kont272],[kont273(stack_gt([$1]),[$2])])
define([kont273],[ifelse(eval(stack_1st([$1]) [== 0]),1,[kont288(stack_drop([$1]),[$2])],[kont278(stack_drop([$1]),[$2])])])
define([kont278],[kont283([64:$1],[$2])])
define([kont283],[kont288(stack_drop([$1]),store([var11],[$2],stack_1st([$1])))])
define([kont288],[kont293(fetch([var6],[$2])[:$1],[$2])])
define([kont293],[kont298(stack_drop([$1]),store([var12],[$2],stack_1st([$1])))])
define([kont298],[kont303(fetch([var10],[$2])[:$1],[$2])])
define([kont303],[kont308(fetch([var9],[$2])[:$1],[$2])])
define([kont308],[kont309(stack_mul([$1]),[$2])])
define([kont309],[kont314([100:$1],[$2])])
define([kont314],[kont315(stack_div([$1]),[$2])])
define([kont315],[kont320(fetch([var7],[$2])[:$1],[$2])])
define([kont320],[kont321(stack_add([$1]),[$2])])
define([kont321],[kont326(stack_drop([$1]),store([var9],[$2],stack_1st([$1])))])
define([kont326],[kont331(fetch([var13],[$2])[:$1],[$2])])
define([kont331],[kont336(fetch([var14],[$2])[:$1],[$2])])
define([kont336],[kont337(stack_sub([$1]),[$2])])
define([kont337],[kont342(fetch([var8],[$2])[:$1],[$2])])
define([kont342],[kont343(stack_add([$1]),[$2])])
define([kont343],[kont348(stack_drop([$1]),store([var10],[$2],stack_1st([$1])))])
define([kont348],[kont353(fetch([var12],[$2])[:$1],[$2])])
define([kont353],[kont358([1:$1],[$2])])
define([kont358],[kont359(stack_add([$1]),[$2])])
define([kont359],[kont364(stack_drop([$1]),store([var12],[$2],stack_1st([$1])))])
define([kont364],[kont164([$1],[$2])])
define([kont369],[kont374(fetch([var11],[$2])[:$1],[$2])])
define([kont374],[prtc_1st([$1])[]kont375(stack_drop([$1]),[$2])])
define([kont375],[kont380(fetch([var8],[$2])[:$1],[$2])])
define([kont380],[kont385(fetch([var4],[$2])[:$1],[$2])])
define([kont385],[kont386(stack_add([$1]),[$2])])
define([kont386],[kont391(stack_drop([$1]),store([var8],[$2],stack_1st([$1])))])
define([kont391],[kont108([$1],[$2])])
define([kont396],[kont401([10:$1],[$2])])
define([kont401],[prtc_1st([$1])[]kont402(stack_drop([$1]),[$2])])
define([kont402],[kont407(fetch([var7],[$2])[:$1],[$2])])
define([kont407],[kont412(fetch([var5],[$2])[:$1],[$2])])
define([kont412],[kont413(stack_sub([$1]),[$2])])
define([kont413],[kont418(stack_drop([$1]),store([var7],[$2],stack_1st([$1])))])
define([kont418],[kont82([$1],[$2])])
define([kont423],[])
divert[]dnl
kont0([stack-bottom],initial_vars)[]dnl
</syntaxhighlight>
{{out}}
<pre>$ m4 mandel.m4
1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211
1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222
1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222
1111111111111112222222222222333333333333333333333333333333333333222222222222222222222222222222222222222
1111111111111222222222233333333333333333333333344444456655544443333332222222222222222222222222222222222
1111111111112222222233333333333333333333333444444445567@@6665444444333333222222222222222222222222222222
11111111111222222333333333333333333333334444444445555679@@@@7654444443333333222222222222222222222222222
1111111112222223333333333333333333333444444444455556789@@@@98755544444433333332222222222222222222222222
1111111122223333333333333333333333344444444445556668@@@ @@@76555544444333333322222222222222222222222
1111111222233333333333333333333344444444455566667778@@ @987666555544433333333222222222222222222222
111111122333333333333333333333444444455556@@@@@99@@@@@@ @@@@@@877779@5443333333322222222222222222222
1111112233333333333333333334444455555556679@ @@@ @@@@@@ 8544333333333222222222222222222
1111122333333333333333334445555555556666789@@@ @86554433333333322222222222222222
1111123333333333333444456666555556666778@@ @ @@87655443333333332222222222222222
111123333333344444455568@887789@8777788@@@ @@@@65444333333332222222222222222
111133334444444455555668@@@@@@@@@@@@99@@@ @@765444333333333222222222222222
111133444444445555556778@@@ @@@@ @855444333333333222222222222222
11124444444455555668@99@@ @ @655444433333333322222222222222
11134555556666677789@@ @86655444433333333322222222222222
111 @@876555444433333333322222222222222
11134555556666677789@@ @86655444433333333322222222222222
11124444444455555668@99@@ @ @655444433333333322222222222222
111133444444445555556778@@@ @@@@ @855444333333333222222222222222
111133334444444455555668@@@@@@@@@@@@99@@@ @@765444333333333222222222222222
111123333333344444455568@887789@8777788@@@ @@@@65444333333332222222222222222
1111123333333333333444456666555556666778@@ @ @@87655443333333332222222222222222
1111122333333333333333334445555555556666789@@@ @86554433333333322222222222222222
1111112233333333333333333334444455555556679@ @@@ @@@@@@ 8544333333333222222222222222222
111111122333333333333333333333444444455556@@@@@99@@@@@@ @@@@@@877779@5443333333322222222222222222222
1111111222233333333333333333333344444444455566667778@@ @987666555544433333333222222222222222222222
1111111122223333333333333333333333344444444445556668@@@ @@@76555544444333333322222222222222222222222
1111111112222223333333333333333333333444444444455556789@@@@98755544444433333332222222222222222222222222
11111111111222222333333333333333333333334444444445555679@@@@7654444443333333222222222222222222222222222
1111111111112222222233333333333333333333333444444445567@@6665444444333333222222222222222222222222222222
1111111111111222222222233333333333333333333333344444456655544443333332222222222222222222222222222222222
1111111111111112222222222222333333333333333333333333333333333333222222222222222222222222222222222222222
1111111111111111222222222222222222233333333333333333333333222222222222222222222222222222222222222222222
1111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222
1111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222211</pre>
[[#ALGOL_W|The entry for ALGOL W]] also is based on Rosetta Code's "compiler" task suite.
=={{header|Maple}}==
<syntaxhighlight lang="maple">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,022 ⟶ 9,342:
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,045 ⟶ 9,365:
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,077 ⟶ 9,397:
shading flat;
end</
To use this function you must specify the:
Line 7,096 ⟶ 9,416:
Sample usage:
<
=={{header|Maxima}}==
Using autoloded package plotdf
<syntaxhighlight lang="maxima">
mandelbrot ([iterations, 30], [x, -2.4, 0.75], [y, -1.2, 1.2],
[grid,320,320])$
</syntaxhighlight>
[[File:MandelbrotMaxima.png|thumb|center]]
=={{header|Metapost}}==
<
outputtemplate:="%j-%c.svg";
outputformat:="svg";
Line 7,142 ⟶ 9,470:
endfig;
end</
Sample usage:
<
=={{header|MiniScript}}==
{{works with|Mini Micro}}
<syntaxhighlight lang="miniscript">ZOOM = 100
MAX_ITER = 40
gfx.clear color.black
Line 7,167 ⟶ 9,496:
end if
end for
end for</
{{output}}
[[File:Mandelbrot-MiniScript.png|frameless]]
=={{header|Modula-3}}==
<
IMPORT Wr, Stdio, Fmt, Word;
Line 7,227 ⟶ 9,558:
END;
END;
END Mandelbrot.</
=={{header|MySQL}}==
Line 7,233 ⟶ 9,564:
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,330 ⟶ 9,661:
INTO OUTFILE '/tmp/image.ppm'
FROM points;
</syntaxhighlight>
=={{header|Nim}}==
Line 7,338 ⟶ 9,669:
{{trans|Python}}
<
proc inMandelbrotSet(c: Complex, maxEscapeIterations = 50): bool =
Line 7,357 ⟶ 9,688:
result.add('\n')
echo mandelbrotImage(1.0, -0.05, -2.0, 0.0315, 40, 80)</
{{out}}
Line 7,401 ⟶ 9,732:
{{trans|Julia}}
{{libheader|imageman}}
<
import imageman
Line 7,437 ⟶ 9,768:
img[x - 1, y - 1] = ColorRGBF64(color)
img.savePNG("mandelbrot.png", compression = 9)</
=={{header|ObjectIcon}}==
A simple interactive graphics program that can dump PNG images. An escape-time algorithm is used to set the opacity of black on white.
You can run it with <code>oiscript the-file-name-you-gave-it.icn</code>. Or you can compile it to an executable intermediate code with <code>oit the-file-name-you-gave-it.icn</code> and then run <code>./the-file-name-you-gave-it</code>
<syntaxhighlight lang="objecticon">
# -*- ObjectIcon -*-
import graphics
import ipl.graphics
import io
import util(Math)
procedure main ()
local w
local width, height
local xcenter, ycenter, pixels_per_unit, max_iter
local zoom_ratio
write ("q or Q : quit")
write ("left press : recenter")
write ("+ : zoom in")
write ("- : zoom in")
write ("2 .. 9 : set zoom ratio")
write ("o or O : restore original")
write ("p or P : dump to a PNG")
width := 400
height := 400
pixels_per_unit := 150
max_iter := 200
zoom_ratio := 2
xcenter := -0.75
ycenter := 0.0
w := Window().
set_size(width, height).
set_resize(&yes).
set_bg("white").
set_canvas("normal") | stop(&why)
event_loop (w, xcenter, ycenter, pixels_per_unit, max_iter,
zoom_ratio)
end
procedure event_loop (w, xcenter, ycenter, pixels_per_unit,
max_iter, zoom_ratio)
local event
local xy
local png_number, png_name
local redraw
local width, height
local xleft, ytop
local i, j
local cx, cy, step
local iter, color
png_number := 1
redraw := &yes
repeat
{
if \redraw then
{
w.erase_area()
step := 1.0 / pixels_per_unit
width := w.get_width()
height := w.get_height()
xleft := xcenter - (width / (2.0 * pixels_per_unit))
ytop := ycenter + (height / (2.0 * pixels_per_unit))
cx := xleft
cy := ytop
j := 0
i := 0
redraw := &no
}
if j ~= height then
{
iter := count_mandelbrot_iterations (cx, cy, max_iter)
color := map_iterations_to_color (max_iter, iter)
w.set_fg (color)
w.draw_point (i, j)
i +:= 1; cx +:= step
if i = width then
{
i := 0; cx := xleft
j +:= 1; cy -:= step
}
}
if *w.pending() ~= 0 then
{
event := w.event()
case event[1] of
{
QuitEvents():
exit()
Mouse.LEFT_PRESS:
{
xy := window_coords_to_point (w, event[2], event[3],
xcenter, ycenter,
pixels_per_unit)
xcenter := xy[1]
ycenter := xy[2]
redraw := &yes
}
"+":
{
pixels_per_unit := zoom_ratio * pixels_per_unit
redraw := &yes
}
"-":
{
pixels_per_unit :=
max (1, (1.0 / zoom_ratio) * pixels_per_unit)
redraw := &yes
}
!"23456789":
zoom_ratio := integer(event[1])
!"oO":
{
pixels_per_unit := 150
max_iter := 200
zoom_ratio := 2
xcenter := -0.75
ycenter := 0.0
redraw := &yes
}
!"pP":
{
png_name := "mandelbrot-image-" || png_number || ".png"
png_number +:= 1
w.get_pixels().to_file(png_name)
write ("Wrote ", png_name)
}
Window.RESIZE:
redraw := &yes
}
WDelay(w, 100)
}
}
end
procedure count_mandelbrot_iterations (cx, cy, max_iter)
local x, y, xsquared, ysquared, iter, tmp
x := 0
y := 0
iter := 0
until (iter = max_iter |
4 < (xsquared := x * x) + (ysquared := y * y)) do
{
tmp := xsquared - ysquared + cx
y := (2 * x * y) + cy
x := tmp
iter +:= 1
}
return iter
end
procedure map_iterations_to_color (max_iter, iter)
return "black " ||
integer((Math.log (iter) * 100.0) / Math.log (max_iter)) ||
"%"
end
procedure window_coords_to_point (w, xcoord, ycoord,
xcenter, ycenter,
pixels_per_unit)
local x, y
x := xcenter +
(((2.0 * xcoord) - w.get_width()) / (2.0 * pixels_per_unit))
y := ycenter +
((w.get_height() - (2.0 * ycoord)) / (2.0 * pixels_per_unit))
return [x, y]
end
</syntaxhighlight>
{{out}}
An example of a dumped PNG:
[[File:Mandelbrot task OI sampleimage.png|thumb|none|alt=A sample of seahorse valley from the Object Icon program.]]
=={{header|OCaml}}==
<
let mandelbrot xMin xMax yMin yMax xPixels yPixels maxIter =
Line 7,467 ⟶ 9,999:
done;;
mandelbrot (-1.5) 0.5 (-1.0) 1.0 500 500 200;;</
=={{header|Octave}}==
Line 7,473 ⟶ 10,005:
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,506 ⟶ 10,038:
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,532 ⟶ 10,064:
z = abs(z);
end
</syntaxhighlight>
=={{header|Ol}}==
<
(define x-size 59)
(define y-size 21)
Line 7,565 ⟶ 10,097:
(print)))
(iota y-size))
</syntaxhighlight>
Output:
Line 7,593 ⟶ 10,125:
=={{header|OpenEdge/Progress}}==
<
DEFINE VARIABLE X1 AS DECIMAL NO-UNDO INIT 50.
DEFINE VARIABLE Y1 AS DECIMAL NO-UNDO INIT 21.
Line 7,637 ⟶ 10,169:
MESSAGE print_str.
OUTPUT CLOSE.
</
=={{header|PARI/GP}}==
Define function mandelbrot():
<
{
forstep(y=-1, 1, 0.05,
Line 7,647 ⟶ 10,179:
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 7,694 ⟶ 10,226:
=={{header|Pascal}}==
{{trans|C}}
<
{$IFDEF FPC}
Line 7,789 ⟶ 10,321:
close(outfile);
end.</
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude str.uh
###sysinclude system.uh
###sysinclude X.uh
$ff0000 sto szin
300 sto maxiter
maxypixel sto YRES
maxxpixel sto XRES
myscreen "Mandelbrot" @YRES @XRES graphic
#g
@YRES 2 / (#d) sto y2
@YRES 2 / (#d) sto x2
@XRES i: {{
@YRES {{
{{}}§i #g !(#d) 480. - @x2 - @x2 /
sto xx
{{}} #g !(#d) @y2 - @y2 /
sto yy
zero#d xa zero#d ya zero iter
#d
ciklus:
@xa dup* @ya dup* - @xx +
@xa 2. * @ya * @yy + sto ya
sto xa ++()#g iter
@xa dup* @ya dup* + 4. > @iter @maxiter >=#g |#g then §ciklusvége
goto §ciklus
ciklusvége:
@iter @maxiter ==#g {
myscreen {{}} {{}}§i @szin setpixel
}{
myscreen {{}} {{}}§i @iter 64 *#g setpixel
}
}}
}}
myscreen 10000 key?
vége: myscreen inv graphic
//."A lenyomott billentyű: " kprintnl
end
{ „xx” }
{ „x2” }
{ „yy” }
{ „y2” }
{ „xa” }
{ „ya” }
{ „iter” }
{ „maxiter” }
{ „szin” }
{ „YRES” }
{ „XRES” }
{ „myscreen” }
</syntaxhighlight>
{{out}}
[[File:Peri_mandelbrot.png]]
=={{header|Perl}}==
translation / optimization of the ruby solution
<
sub mandelbrot {
Line 7,807 ⟶ 10,398:
{print mandelbrot($x + $y * i) ? ' ' : '#'}
print "\n"
}</
=={{header|Phix}}==
;Ascii
This is included in the distribution (with some extra validation) as demo\mandle.exw
<syntaxhighlight lang="phix">--
-- Mandlebrot set in ascii art demo.
--
Line 7,836 ⟶ 10,427:
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,079 ⟶ 10,670:
WinMain(Main,SW_NORMAL)
void = deleteDib(0)</
=={{header|PHP}}==
Line 8,087 ⟶ 10,678:
[[File:Mandel-php.png|thumb|right|Sample output]]
<
$max_x=1;
$min_y=-1;
Line 8,126 ⟶ 10,717:
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,160 ⟶ 10,751:
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,215 ⟶ 10,806:
=={{header|PicoLisp}}==
<
(let Ppm (make (do 300 (link (need 400))))
Line 8,232 ⟶ 10,823:
(prinl 400 " " 300)
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) )</
=={{header|PostScript}}==
<
%%BoundingBox: 0 0 300 200
%%EndComments
Line 8,280 ⟶ 10,871:
showpage
origstate restore
%%EOF</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$x = $y = $i = $j = $r = -16
$colors = [Enum]::GetValues([System.ConsoleColor])
Line 8,304 ⟶ 10,895:
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,367 ⟶ 10,958:
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,422 ⟶ 11,013:
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,464 ⟶ 11,055:
compute_RGB(CX, CY, Tmp, ZY1, Iter1, IterF).
compute_RGB(_CX, _CY, _ZX, _ZY, Iter, Iter).</
[[FILE:Mandelbrot.jpg]]
Line 8,471 ⟶ 11,062:
=={{header|Python}}==
Translation of the ruby solution
<
try:
from functools import reduce
Line 8,489 ⟶ 11,080:
print("\n".join("".join(row) for row in rows))
</syntaxhighlight>
A more "Pythonic" version of the code:
<
import math
Line 8,507 ⟶ 11,098:
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,536 ⟶ 11,127:
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,566 ⟶ 11,157:
cmap=plt.cm.prism,
extent=(X.min(), X.max(), Y.min(), Y.max()))
plt.show()</
===Normal Map Effect, Mercator Projection and Deep Zoom Images===
'''Normalization, Distance Estimation and Boundary Detection'''
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 Arnaud Chéritat: [https://www.math.univ-toulouse.fr/~cheritat/wiki-draw/index.php/Mandelbrot_set#Boundary_detection_methods_via_distance_estimators ''Boundary detection methods via distance estimators'']). Partial antialiasing is used for boundary detection.
<syntaxhighlight lang="python">import numpy as np
import matplotlib.pyplot as plt
d, h = 800, 500 # pixel density (= image width) and image height
n, r = 200, 500 # number of iterations and escape radius (r > 2)
x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)
A, B = np.meshgrid(x - 1, y - h / d)
C = 2.0 * (A + B * 1j) - 0.5
Z, dZ = np.zeros_like(C), np.zeros_like(C)
D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)
for k in range(n):
S[M], T[M] = S[M] + np.exp(- abs(Z[M])), T[M] + 1
Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1
plt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_set_1.png", dpi=200)
N = abs(Z) >= r # normalized iteration count
T[N] = T[N] - np.log2(np.log(np.abs(Z[N])) / np.log(r))
plt.imshow(T ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("
N = abs(Z) > 2 # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])
plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_set_3.png", dpi=200)
N, thickness = D > 0, 0.01 # boundary detection
D[N] = np.maximum(1 - D[N] / thickness, 0)
plt.imshow(D ** 2.0, cmap=plt.cm.binary, origin="lower")
plt.savefig("Mandelbrot_set_4.png", dpi=200)</syntaxhighlight>
'''Normal Map Effect and Stripe Average Coloring'''
The Mandelbrot set is represented using Normal Maps and Stripe Average Coloring by Jussi Härkönen (cf. Arnaud Chéritat: [https://www.math.univ-toulouse.fr/~cheritat/wiki-draw/index.php/Mandelbrot_set#Normal_map_effect ''Normal map effect'']). Note that the second derivative (ddZ) grows very fast, so the second method can only be used for small iteration numbers (n <= 400). See also the picture in section [https://www.math.univ-toulouse.fr/~cheritat/wiki-draw/index.php/Mandelbrot_set#Mixing_it_all ''Mixing it all''] and [https://www.shadertoy.com/view/wtscDX Julia Stripes] on Shadertoy. To get a stripe pattern similar to that of Arnaud Chéritat, one can increase the ''density'' of the stripes, use ''cos'' instead of ''sin'', and set the colormap to ''binary''.
<syntaxhighlight lang="python">import numpy as np
import matplotlib.pyplot as plt
d, h = 800, 500 # pixel density (= image width) and image height
n, r = 200, 500 # number of iterations and escape radius (r > 2)
direction, height = 45.0, 1.5 # direction and height of the light
density, intensity = 4.0, 0.5 # density and intensity of the stripes
x = np.linspace(0, 2, num=d+1)
Line 8,635 ⟶ 11,221:
A, B = np.meshgrid(x - 1, y - h / d)
C = (2.0
Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)
for k in range(n):
M = abs(Z) < r
S[M], T[M] = S[M] + np.
Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M])
N = abs(Z) >= r # basic normal map effect and stripe average coloring (potential function)
P, Q = S[N] / T[N], (S[N] + np.sin(density * np.angle(Z[N]))) / (T[N] + 1)
U, V = Z[N] / dZ[N], 1 + (np.log2(np.log(np.abs(Z[N])) / np.log(r)) * (P - Q) + Q) * intensity
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) / (1 + height), 0)
plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower")
plt.savefig("Mandelbrot_normal_map_1.png", dpi=200)
N = abs(Z) > 2 # advanced normal map effect using higher derivatives (distance estimation)
U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N]))
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0)
plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower")
plt.savefig("Mandelbrot_normal_map_2.png", dpi=200)</syntaxhighlight>
'''Mercator Mandelbrot Maps and Zoom Images'''
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'']). The maximum magnification is about <math>e ^ {2 \pi \cdot h / d} = e ^ {2 \pi \cdot 5.5} \approx 535.5 ^ {5.5} \approx 10 ^ {15}</math>, which is also the maximum for 64-bit arithmetic. Note that Anders Sandberg uses a different scaling. He uses <math>10 ^ {3 \cdot h / d} = 1000 ^ {h / d}</math> instead of <math>e ^ {2 \pi \cdot h / d} \approx 535.5 ^ {h / d}</math>, so his images appear somewhat compressed in comparison (but not much, because <math>1000 ^ {5.0} \approx 535.5 ^ {5.5}</math>). 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. See also [https://commons.wikimedia.org/wiki/File:Mandelbrot_sequence_new.gif ''Mandelbrot sequence new''] on Wikimedia for a zoom animation to the given coordinates.
<syntaxhighlight lang="python">import numpy as np
import matplotlib.pyplot as plt
d, h = 200, 1200 # pixel density (= image width) and image height
n, r =
a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html
b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800
x = np.linspace(0, 2, num=d+1)
Line 8,676 ⟶ 11,264:
A, B = np.meshgrid(x * np.pi, y * np.pi)
C =
Z, dZ = np.zeros_like(C), np.zeros_like(C)
Line 8,682 ⟶ 11,270:
for k in range(n):
M =
Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1
N = abs(Z) > 2 # exterior distance estimation
D[N] =
plt.imshow(D.T ** 0.
plt.savefig("Mercator_Mandelbrot_map.png", dpi=200)
X, Y = C.real, C.imag # zoom images (adjust circle size
R, c, z =
fig, ax = plt.subplots(2, 2, figsize=(12, 12))
ax[0,
ax[0,
ax[1,
ax[1,
plt.savefig("
'''Perturbation Theory and Deep Mercator Maps'''
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. Rebasing is used to reduce glitches. 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#avoiding-loss-of-precision Avoiding loss of precision] (Fractalshades) for details. See also the image [https://www.flickr.com/photos/arenamontanus/3430921497/in/album-72157615740829949/ Deeper Mercator Mandelbrot] by Anders Sandberg.
<syntaxhighlight lang="python">import numpy as np
import matplotlib.pyplot as plt
import decimal as dc # decimal floating point arithmetic with arbitrary precision
dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits)
d, h = 50, 1000 # pixel density (= image width) and image height
n, r = 80000, 100000 # number of iterations and escape radius (r > 2)
a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291")
b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025")
S = np.zeros(n+1, dtype=np.complex128)
u, v = dc.Decimal(0), dc.Decimal(0)
for k in range(n+1):
S[k] = float(u) + float(v) * 1j
if u ** 2 + v ** 2 < r ** 2:
u, v = u ** 2 - v ** 2 + a, 2 * u * v + b
else:
print("The reference sequence diverges within %s iterations." % k)
break
x = np.linspace(0, 2, num=d+1, dtype=np.float64)
y = np.linspace(0, 2 * h / d, num=h+1, dtype=np.float64)
A, B = np.meshgrid(x * np.pi, y * np.pi)
C = 8.0 * np.exp((A + B * 1j) * 1j)
E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)
D, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64)
for k in range(n):
Z2 = Z.real ** 2 + Z.imag ** 2
M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2
E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero
E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1
Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1
N = abs(Z) > 2 # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])
plt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin="lower")
plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200)</syntaxhighlight>
You can only rebase to the beginning of the reference sequence. If you want to change from current reference point <math>S_i</math> to reference point <math>S_j</math>, the difference <math>\epsilon_j = z - s_j</math> must be calculated. With this subtraction, however, the entire precision is lost due to [https://en.wikipedia.org/wiki/Catastrophic_cancellation catastrophic cancellation]. Only at the first reference point <math>S_0 = (0, 0)</math> there is no cancellation because <math>\epsilon_0 = z - s_0 = z - 0 = z</math>. Therefore, the rebasing condition <math>|z| < |\epsilon_i|</math> can also be written as <math>|\epsilon_0| < |\epsilon_i|</math> or as <math>|z - s_0| < |z - s_i|</math>. This keeps the differences to the reference sequence as small as possible: rebasing occurs when the distance to reference point <math>S_0</math> is smaller than the distance to the current reference point <math>S_i</math>.
===Python - "One liner"===
<syntaxhighlight lang="python">
print(
'\n'.join(
''.join(
' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2]
for x in range(-100,25)
)
for y in range(-50,50)
))
</syntaxhighlight>
===Python - "Functional"===
Based on the "One liner" approach.
<syntaxhighlight lang="python">
from functools import reduce
def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2]
print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50)))
</syntaxhighlight>
=={{header|q}}==
<syntaxhighlight lang="q">/adapted from https://www.linkedin.com/pulse/want-work-k-1010data-michal-wallace
q)s:{(.[-]x*x),2*prd x} / complex square (x is R,Im pair)
q)m:{floor sqrt sum x*x} / magnitude (distance from origin)
q)d: 120 60 / dimensions of the picture
q)t: -88 -30 / camera translation
q)f: reciprocal 40 20 / scale factor
q)c: (,/:\:) . f * t + til each d / complex plane near mandelbrot set
q)z: d # enlist 0 0 / 3d array of zeroes in same shape
q)mb: c+ (s'')@ / mandelbrot: s(z) + c
q)r: 1 _ 8 mb\z / collect 8 times
q)o: " 12345678"@ sum 2<m'''[r] / "color" by how soon point "escapes"
q)-1 "\n"sv flip o; / transpose and print the output
</syntaxhighlight>
<pre>555555555555555555555556666666666666665555555555555555555555555555555555555555555555555555555555555666666666666666666666
555555555555555555556666666666666555555555555555555555555555555555555555555555555555555555555555555555556666666666666666
555555555555555556666666666666555555555555555555555555555555555555555555555555555555555555555555555555555556666666666666
555555555555555666666666665555555555555555555555555555555555555555555556666666666666666666555555555555555555555666666666
555555555555666666666666555555555555555555555555555555555555555556666666666666666666666666666665555555555555555556666666
555555555566666666666555555555555555555555555555555555555555566666666555555555555555555555566666665555555555555555556666
555555556666666666655555555555555555555555555555555555556666666655555555555555555555555555555555666665555555555555555566
555555666666666655555555555555555555555555555555555566666666555555555555555554444444444555555555555666665555555555555555
55556666666666555555555555555555555555555555555566666666555555555555555555444432 13344444555555555555666655555555555555
556666666666655555555555555555555555555555555666666665555555555555555554444443321 1222234445555555555556666655555555555
666666666665555555555555555555555555555556666666665555555555555555555444444433321 3344455555555555566666555555555
666666666555555555555555555555555555556666666665555555555555555555544444443332211 22334444455555555555666655555555
666666665555555555555555555555555566666666665555555555555555555544444444333321 12233444444555555555566666555555
6666665555555555555555555555555666666666665555555555555555555444444443333322 123334444444555555555666655555
6666655555555555555555555555666666666665555555555555555554444444433333332221 22333344444445555555566666555
666655555555555555555555566666666666555555555555555554444444443333322222211 11223333333444455555556666655
666555555555555555555556666666666555555555555555544444444444332111 111 11222222 23444555555666665
665555555555555555556666666666555555555555555444444444444333321 11 2334455555566666
655555555555555555666666665555555555555544444444444444433333221 134445555556666
555555555555555566666665555555555555544444444444444433333332211 234444555555666
555555555555556666655555555555555444444444444333333333332221 1233444555555566
55555555555566665555555555555544444332233333333333322222211 1223344455555566
5555555555666555555555555554444443331 1122222111122222111 2344455555556
5555555566655555555555555444444433321 1 344455555556
5555555666555555555555544444444333221 12334455555555
5555566655555555555554444444433332221 2344445555555
555566655555555555444444443333322111 12344445555555
5556665555555554444443333333221 23344445555555
556666555544444443333333322221 233344445555555
55666555444333322 122111111 12233444445555555
55666555 12233444445555555
55666555444333322 122111111 12233444445555555
556666555544444443333333322221 233344445555555
5556665555555554444443333333221 23344445555555
555566655555555555444444443333322111 12344445555555
5555566655555555555554444444433332221 2344445555555
5555555666555555555555544444444333221 12334455555555
5555555566655555555555555444444433321 1 344455555556
5555555555666555555555555554444443331 1122222111122222111 2344455555556
55555555555566665555555555555544444332233333333333322222211 1223344455555566
555555555555556666655555555555555444444444444333333333332221 1233444555555566
555555555555555566666665555555555555544444444444444433333332211 234444555555666
655555555555555555666666665555555555555544444444444444433333221 134445555556666
665555555555555555556666666666555555555555555444444444444333321 11 2334455555566666
666555555555555555555556666666666555555555555555544444444444332111 111 11222222 23444555555666665
666655555555555555555555566666666666555555555555555554444444443333322222211 11223333333444455555556666655
6666655555555555555555555555666666666665555555555555555554444444433333332221 22333344444445555555566666555
6666665555555555555555555555555666666666665555555555555555555444444443333322 123334444444555555555666655555
666666665555555555555555555555555566666666665555555555555555555544444444333321 12233444444555555555566666555555
666666666555555555555555555555555555556666666665555555555555555555544444443332211 22334444455555555555666655555555
666666666665555555555555555555555555555556666666665555555555555555555444444433321 3344455555555555566666555555555
556666666666655555555555555555555555555555555666666665555555555555555554444443321 1222234445555555555556666655555555555
55556666666666555555555555555555555555555555555566666666555555555555555555444432 13344444555555555555666655555555555555
555555666666666655555555555555555555555555555555555566666666555555555555555554444444444555555555555666665555555555555555
555555556666666666655555555555555555555555555555555555556666666655555555555555555555555555555555666665555555555555555566
555555555566666666666555555555555555555555555555555555555555566666666555555555555555555555566666665555555555555555556666
555555555555666666666666555555555555555555555555555555555555555556666666666666666666666666666665555555555555555556666666
555555555555555666666666665555555555555555555555555555555555555555555556666666666666666666555555555555555555555666666666
555555555555555556666666666666555555555555555555555555555555555555555555555555555555555555555555555555555556666666666666
555555555555555555556666666666666555555555555555555555555555555555555555555555555555555555555555555555556666666666666666</pre>
=={{header|R}}==
<
#we iterate all active points in the same array operation,
#and keeping track of which points are still iterating.
Line 8,757 ⟶ 11,462:
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 8,776 ⟶ 11,481:
X[, , k] <- exp(-abs(Z)) # capture results
}
write.gif(X, "Mandelbrot.gif", col = jet.colors, delay = 100)</
=={{header|Racket}}==
<
#lang racket
Line 8,806 ⟶ 11,511:
(mandelbrot 300 200)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|
Using the [https://docs.raku.org/language/statement-prefixes#hyper,_race hyper statement prefix] for concurrency, the code below produces a [[Write ppm file|graymap]] to standard output.
[[File:mandelbrot-raku.jpg|300px|thumb|right]]
<syntaxhighlight lang=raku>constant MAX-ITERATIONS = 64;
my $width = +(@*ARGS[0] // 800);
my $height = $width + $width %% 2;
say "P2";
say "$width $height";
say MAX-ITERATIONS;
sub cut(Range $r, UInt $n where $n > 1 --> Seq) {
$r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max
}
my @re = cut(-2 .. 1/2, $width);
my @im = cut( 0 .. 5/4, 1 + ($height div 2)) X* 1i;
sub mandelbrot(Complex $z is copy, Complex $c --> Int) {
for 1 .. MAX-ITERATIONS {
$z = $z*$z + $c;
return $_ if $z.abs > 2;
}
return 0;
}
my @lines = hyper for @im X+ @re {
mandelbrot(0i, $_);
}.rotor($width);
.put for @lines[1..*].reverse;
.put for @lines;</syntaxhighlight>
<!-- # Not sure this version is that much modern or faster now.
Alternately, a more modern, faster version.
[[File:Mandelbrot-set-perl6.png|300px|thumb|right]]
<syntaxhighlight lang="perl6" line>use Image::PNG::Portable;
my ($w, $h) = 800, 800;
Line 8,915 ⟶ 11,600:
} ).map: ((*+$m) * 255).Int]
}
}</
-->
=={{header|REXX}}==
Line 8,922 ⟶ 11,608:
{{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 8,938 ⟶ 11,624:
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 8,966 ⟶ 11,652:
===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 8,982 ⟶ 11,668:
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,010 ⟶ 11,696:
===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,029 ⟶ 11,715:
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,081 ⟶ 11,767:
=={{header|Ring}}==
<
load "guilib.ring"
Line 9,135 ⟶ 11,821:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
Output:
Line 9,143 ⟶ 11,829:
=={{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,154 ⟶ 11,840:
end
puts
end</
{{trans|Tcl}}
Uses [[Raster graphics operations/Ruby]]
<
require_relative 'raster_graphics'
Line 9,196 ⟶ 11,882:
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,239 ⟶ 11,925:
size(900, 600)
end
</syntaxhighlight>
=={{header|Rust}}==
Dependencies: image, num-complex
<
extern crate num_complex;
use num_complex::Complex;
Line 9,284 ⟶ 11,969:
// Save image
imgbuf.save("fractal.png").unwrap();
}</
=={{header|Sass/SCSS}}==
<
$canvasWidth: 200;
$canvasHeight: 200;
Line 9,334 ⟶ 12,019:
}
</syntaxhighlight>
=={{header|Scala}}==
Line 9,340 ⟶ 12,025:
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,382 ⟶ 12,067:
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}}==
===A simple implementation for many Scheme implementations===
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,433 ⟶ 12,121:
(begin (display (pixel i j)) (newline))))))))
(plot)</
===An interactive program for CHICKEN Scheme===
{{trans|ObjectIcon}}
{{works with|CHICKEN Scheme|5.3.0}}
You will need several CHICKEN "eggs", which can be deduced from the imports.
Compile with (for example) <code>csc -O3 mandelbrot_task_CHICKEN.scm</code>.
<syntaxhighlight lang="scheme">
;; A program written for CHICKEN Scheme version 5.3.0 and various
;; eggs.
(import (r7rs))
(import (scheme base))
(import (scheme case-lambda))
(import (scheme inexact))
(import (prefix sdl2 "sdl2:"))
(import (prefix imlib2 "imlib2:"))
(import (format))
(import (matchable))
(import (simple-exceptions))
(define sdl2-subsystems-used '(events video))
;; ------------------------------
;; Basics for using the sdl2 egg:
(sdl2:set-main-ready!)
(sdl2:init! sdl2-subsystems-used)
(on-exit sdl2:quit!)
(current-exception-handler
(let ((original-handler (current-exception-handler)))
(lambda (exception)
(sdl2:quit!)
(original-handler exception))))
;; ------------------------------
(define-record-type <mandel-params>
(%%make-mandel-params)
mandel-params?
(window ref-window set-window!)
(xcenter ref-xcenter set-xcenter!)
(ycenter ref-ycenter set-ycenter!)
(pixels-per-unit ref-pixels-per-unit set-pixels-per-unit!)
(pixels-per-event-check ref-pixels-per-event-check
set-pixels-per-event-check!)
(max-escape-time ref-max-escape-time set-max-escape-time!))
(define initial-width 400)
(define initial-height 400)
(define initial-xcenter -3/4)
(define initial-ycenter 0)
(define initial-pixels-per-unit 150)
(define initial-pixels-per-event-check 1000)
(define initial-max-escape-time 1000)
(define (make-mandel-params window)
(let ((params (%%make-mandel-params)))
(set-window! params window)
(set-xcenter! params initial-xcenter)
(set-ycenter! params initial-ycenter)
(set-pixels-per-unit! params initial-pixels-per-unit)
(set-pixels-per-event-check! params
initial-pixels-per-event-check)
(set-max-escape-time! params initial-max-escape-time)
params))
(define window (sdl2:create-window! "mandelbrot set task"
'centered 'centered
initial-width initial-height
'()))
(define params (make-mandel-params window))
(define empty-color (sdl2:make-color 200 200 200))
(define (clear-mandel!)
(sdl2:fill-rect! (sdl2:window-surface (ref-window params))
#f empty-color)
(sdl2:update-window-surface! window))
(define drawing? #t)
(define redraw? #f)
(define (draw-mandel! event-checker)
(clear-mandel!)
(let repeat ()
(let*-values
(((window) (ref-window params))
((width height) (sdl2:window-size window)))
(let* ((xcenter (ref-xcenter params))
(ycenter (ref-ycenter params))
(pixels-per-unit (ref-pixels-per-unit params))
(pixels-per-event-check
(ref-pixels-per-event-check params))
(max-escape-time (ref-max-escape-time params))
(step (/ 1.0 pixels-per-unit))
(xleft (- xcenter (/ width (* 2.0 pixels-per-unit))))
(ytop (+ ycenter (/ height (* 2.0 pixels-per-unit))))
(pixel-count 0))
(do ((j 0 (+ j 1))
(cy ytop (- cy step)))
((= j height))
(do ((i 0 (+ i 1))
(cx xleft (+ cx step)))
((= i width))
(let* ((color (compute-color-by-escape-time-algorithm
cx cy max-escape-time)))
(sdl2:surface-set! (sdl2:window-surface window)
i j color)
(if (= pixel-count pixels-per-event-check)
(let ((event-checker (call/cc event-checker)))
(cond (redraw?
(set! redraw? #f)
(clear-mandel!)
(repeat)))
(set! pixel-count 0))
(set! pixel-count (+ pixel-count 1)))))
;; Display a row.
(sdl2:update-window-surface! window))))
(set! drawing? #f)
(repeat)))
(define (compute-color-by-escape-time-algorithm
cx cy max-escape-time)
(escape-time->color (compute-escape-time cx cy max-escape-time)
max-escape-time))
(define (compute-escape-time cx cy max-escape-time)
(let loop ((x 0.0)
(y 0.0)
(iter 0))
(if (= iter max-escape-time)
iter
(let ((xsquared (* x x))
(ysquared (* y y)))
(if (< 4 (+ xsquared ysquared))
iter
(let ((x (+ cx (- xsquared ysquared)))
(y (+ cy (* (+ x x) y))))
(loop x y (+ iter 1))))))))
(define (escape-time->color escape-time max-escape-time)
;; This is a very naive and ad hoc algorithm for choosing colors,
;; but hopefully will suffice for the task. With this algorithm, at
;; least one can zoom in and see some of the fractal-like structures
;; out on the filaments.
(let* ((initial-ppu initial-pixels-per-unit)
(ppu (ref-pixels-per-unit params))
(fraction (* (/ (log escape-time) (log max-escape-time))))
(fraction (if (= fraction 1.0)
fraction
(* fraction
(/ (log initial-ppu)
(log (max initial-ppu (* 0.05 ppu)))))))
(value (- 255 (min 255 (exact-rounded (* fraction 255))))))
(sdl2:make-color value value value)))
(define (exact-rounded x)
(exact (round x)))
(define (event-loop)
(define event (sdl2:make-event))
(define painter draw-mandel!)
(define zoom-ratio 2)
(define (recenter! xcoord ycoord)
(let*-values
(((window) (ref-window params))
((width height) (sdl2:window-size window))
((ppu) (ref-pixels-per-unit params)))
(set-xcenter! params
(+ (ref-xcenter params)
(/ (- (* 2.0 xcoord) width) (* 2.0 ppu))))
(set-ycenter! params
(+ (ref-ycenter params)
(/ (- height (* 2.0 ycoord)) (* 2.0 ppu))))))
(define (zoom-in!)
(let* ((ppu (ref-pixels-per-unit params))
(ppu (* ppu zoom-ratio)))
(set-pixels-per-unit! params ppu)))
(define (zoom-out!)
(let* ((ppu (ref-pixels-per-unit params))
(ppu (* (/ 1.0 zoom-ratio) ppu)))
(set-pixels-per-unit! params (max 1 ppu))))
(define (restore-original-settings!)
(set-xcenter! params initial-xcenter)
(set-ycenter! params initial-ycenter)
(set-pixels-per-unit! params initial-pixels-per-unit)
(set-pixels-per-event-check!
params initial-pixels-per-event-check)
(set-max-escape-time! params initial-max-escape-time)
(set! zoom-ratio 2))
(define dump-image! ; Really this should put up a dialog.
(let ((dump-number 1))
(lambda ()
(let*-values
(((window) (ref-window params))
((width height) (sdl2:window-size window))
((surface) (sdl2:window-surface window)))
(let ((filename (string-append "mandelbrot-image-"
(number->string dump-number)
".png"))
(img (imlib2:image-create width height)))
(do ((j 0 (+ j 1)))
((= j height))
(do ((i 0 (+ i 1)))
((= i width))
(let-values
(((r g b a) (sdl2:color->values
(sdl2:surface-ref surface i j))))
(imlib2:image-draw-pixel
img (imlib2:color/rgba r g b a) i j))))
(imlib2:image-alpha-set! img #f)
(imlib2:image-save img filename)
(format #t "~a written~%" filename)
(set! dump-number (+ dump-number 1)))))))
(let loop ()
(when redraw?
(set! drawing? #t))
(when drawing?
(set! painter (call/cc painter)))
(set! redraw? #f)
(if (not (sdl2:poll-event! event))
(loop)
(begin
(match (sdl2:event-type event)
('quit) ; Quit by leaving the loop.
('window
(match (sdl2:window-event-event event)
;; It should be possible to resize the window, but I
;; have not yet figured out how to do this with SDL2
;; and not crash sometimes.
((or 'exposed 'restored)
(sdl2:update-window-surface! (ref-window params))
(loop))
(_ (loop))))
('mouse-button-down
(recenter! (sdl2:mouse-button-event-x event)
(sdl2:mouse-button-event-y event))
(set! redraw? #t)
(loop))
('key-down
(match (sdl2:keyboard-event-sym event)
('q 'quit-by-leaving-the-loop)
((or 'plus 'kp-plus)
(zoom-in!)
(set! redraw? #t)
(loop))
((or 'minus 'kp-minus)
(zoom-out!)
(set! redraw? #t)
(loop))
((or 'n-2 'kp-2)
(set! zoom-ratio 2)
(loop))
((or 'n-3 'kp-3)
(set! zoom-ratio 3)
(loop))
((or 'n-4 'kp-4)
(set! zoom-ratio 4)
(loop))
((or 'n-5 'kp-5)
(set! zoom-ratio 5)
(loop))
((or 'n-6 'kp-6)
(set! zoom-ratio 6)
(loop))
((or 'n-7 'kp-7)
(set! zoom-ratio 7)
(loop))
((or 'n-8 'kp-8)
(set! zoom-ratio 8)
(loop))
((or 'n-9 'kp-9)
(set! zoom-ratio 9)
(loop))
('o
(restore-original-settings!)
(set! redraw? #t)
(loop))
('p
(dump-image!)
(loop))
(some-key-in-which-we-are-not-interested
(loop))))
(some-event-in-which-we-are-not-interested
(loop)))))))
;; At the least this legend should go in a window, but printing it to
;; the terminal will, hopefully, suffice for the task.
(format #t "~%~8tACTIONS~%")
(format #t "~8t-------~%")
(define fmt "~2t~a~15t: ~a~%")
(format #t fmt "Q key" "quit")
(format #t fmt "mouse button" "recenter")
(format #t fmt "+ key" "zoom in")
(format #t fmt "- key" "zoom in")
(format #t fmt "2 .. 9 key" "set zoom ratio")
(format #t fmt "O key" "restore original")
(format #t fmt "P key" "dump to a PNG")
(format #t "~%")
(event-loop)
</syntaxhighlight>
{{out}}
An example of a PNG dumped by the program while it was zoomed in:
[[File:Mandelbrot task CHICKEN sampleimage.png|thumb|none|alt=A zoomed-in picture of a part of the Mandelbrot set.]]
=={{header|Scratch}}==
Line 9,451 ⟶ 12,454:
# for which the sequence z[n+1] := z[n] ** 2 + z[0] (n >= 0) is bounded.
# Since this program is computing intensive it should be compiled with
#
const integer: pix is 200;
Line 9,483 ⟶ 12,486:
z0 := center + complex(flt(x) * zoom, flt(y) * zoom);
point(x + pix, y + pix, colorTable[iterate(z0)]);
end for;
end for;
end func;
Line 9,501 ⟶ 12,504:
end for;
displayMandelbrotSet(complex(-0.75, 0.0), 1.3 / flt(pix));
readln(KEYBOARD);
end func;
Line 9,510 ⟶ 12,513:
=={{header|SenseTalk}}==
<
put 0 into oImag # Imaginary origin
put 0.5 into mag # Magnification
Line 9,572 ⟶ 12,575:
close file myFile
</syntaxhighlight>
=={{header|SequenceL}}==
'''SequenceL Code for Computing and Coloring:'''<br>
<
import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;
Line 9,663 ⟶ 12,666:
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 9,769 ⟶ 12,772:
return 0;
}</
{{out}}
Line 9,775 ⟶ 12,778:
=={{header|Sidef}}==
<
var c = z
{ z = (z*z + c)
Line 9,788 ⟶ 12,791:
}
print "\n"
}</
=={{header|Simula}}==
{{trans|Scheme}}
<
REAL XCENTRE, YCENTRE, WIDTH, RMAX, XOFFSET, YOFFSET, PIXELSIZE;
INTEGER N, IMAX, JMAX, COLOURMAX;
Line 9,877 ⟶ 12,880:
PLOT;
END;</
=={{header|Spin}}==
Line 9,884 ⟶ 12,887:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 9,927 ⟶ 12,930:
waitcnt(_clkfreq+cnt)
ser.stop</
{{out}}
Line 9,957 ⟶ 12,960:
!!!!!!!!!!!!!!!""""""""""""#####################################""""""""""""""""
</pre>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "mandel" )
@( description, "Create a color image of the Mandelbrot set" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure mandel is
mandel_limit : constant long_float := 4.0; -- reach this? it's the set
max_iterations : constant integer := 128; -- quit if looped this amt
center_r : constant long_float := -0.75; -- center of set (x=real)
center_i : constant long_float := 0.0; -- center of set (i=imag.)
c_r : long_float; -- current point (x=real)
c_i : long_float; -- current point (i=imag.)
loop_count : integer; -- number of iterations
z_r : long_float; -- mandelbot set formula
z_i : long_float; -- variables
z_r2 : long_float;
z_i2 : long_float;
c : pen.canvas_id; -- bush drawing canvas
plot : limited pen.rect; -- rectangle to draw with
s : string;
bits : integer; -- for determining color
red : pen.rgbcomponent;
green: pen.rgbcomponent;
blue : pen.rgbcomponent;
begin
-- create the drawing canvas
pen.new_window_canvas( 200, 200, 32, c );
pen.set_title( c, "Mandelbrot" );
-- loop for the size of the canvas (-50% to +50%)
for i in -50..50 loop
c_i := center_i - long_float(i)*0.025;
pen.wait_to_reveal( c );
for r in -50..50 loop
c_r := center_r - long_float(r)*0.025;
-- Evaluatuate how close point (c_z, c_i ) in complex number space
-- is to the Mandelbrot set. Return a number between 0 and
-- max_iterations. A value of max_iterations implies that the point
-- is probably a member of the Mandelbrot set.
z_r := c_r;
z_i := c_i;
loop_count := 1;
loop
z_i2 := z_i*z_i;
z_r2 := z_r*z_r;
z_i := 2.0 * z_r * z_i + c_i;
z_r := z_r2 - z_i2 + c_r;
loop_count := @+1;
exit when not ( (z_r2 + z_i2 < mandel_limit) and (loop_count /= max_iterations) );
end loop;
-- pick a color based on loop_count (mandelbrot set is black)
if loop_count = max_iterations then
red := 0.0;
green := 0.0;
blue := 0.0;
else
bits := (loop_count and 3 );
red := 100.0-pen.rgbcomponent((100*bits/3));
bits := (loop_count / 3 ) and 3;
green := 100.0-pen.rgbcomponent((100*bits/3));
bits := (loop_count / 27 ) and 2;
blue := 100.0-pen.rgbcomponent((100*bits)/2);
end if;
pen.set_pen_ink( c, red, green, blue );
-- Draw the point, reversing the X axis
pen.set_rect( plot, 100-(r+50),i+50, 100-(r+49), i+51 );
pen.paint_rect( c, plot );
end loop;
pen.reveal( c );
end loop;
? "Press return";
s := get_line;
end mandel;</syntaxhighlight>
=={{header|SPL}}==
<
sfx = -2.5; sfy = -2*h/w; fs = 4/w
#.aaoff()
Line 9,976 ⟶ 13,076:
? n=maxn, <= 0,0,0
<= #.hsv2rgb(n/maxn*360,1,1):3
.</
Line 9,983 ⟶ 13,083:
Using the Swift Numerics package, as well as the C library Quick 'N Dirty BMP imported in Swift.
<
import Numerics
import QDBMP
Line 10,070 ⟶ 13,170:
}
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,104 ⟶ 13,204:
update
}
.mandel configure -cursor {}</
=={{header|TeX}}==
Line 10,110 ⟶ 13,210:
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,128 ⟶ 13,228:
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,135 ⟶ 13,235:
\shade[shading=Mandelbrot set] (0,0) rectangle (4,4);
\end{tikzpicture}
\end{document}</
=={{header|LuaTeX}}==
Line 10,145 ⟶ 13,245:
=={{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,170 ⟶ 13,270:
:End
:End
</syntaxhighlight>
=={{header|Transact-SQL}}==
This is a Transact-SQL version of SQL Server to generate Mandelbrot set. Export the final result to a .ppm file to view the image. More details are available [https://krishnakumarsql.wordpress.com/2023/07/12/drawing-a-colorful-mandelbrot-set-in-sql-server/ here].
<syntaxhighlight lang="Transact-SQL">
-- Mandelbrot Set
-- SQL Server 2017 and above
SET NOCOUNT ON
GO
-- Plot area 800 X 800
DECLARE @width INT = 800
DECLARE @height INT = 800
DECLARE @r_min DECIMAL (10, 8) = -2.5;
DECLARE @r_max DECIMAL (10, 8) = 1.5;
DECLARE @r_step DECIMAL (10, 8) = 0.005;
DECLARE @i_min DECIMAL (10, 8) = -2;
DECLARE @i_max DECIMAL (10, 8) = 2;
DECLARE @i_step DECIMAL (10, 8) = 0.005;
DECLARE @iter INT = 255; -- Iteration
DROP TABLE IF EXISTS dbo.Numbers
DROP TABLE IF EXISTS dbo.mandelbrot_set;
CREATE TABLE dbo.Numbers (n INT);
-- Generate a number table of 1000 rows
;WITH N1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
N2(n) AS (SELECT 1 FROM N1 CROSS JOIN N1 AS b), -- 10*10
N3(n) AS (SELECT 1 FROM N1 CROSS JOIN N2) -- 10*100
INSERT INTO dbo.Numbers (n)
SELECT n = ROW_NUMBER() OVER (ORDER BY n)
FROM N3 ORDER BY n;
/*
-- If the version is SQL Server 2022 and above
INSERT INTO dbo.Numbers (n)
SELECT value FROM GENERATE_SERIES(0, 1000);
*/
CREATE TABLE dbo.mandelbrot_set
(
a INT,
b INT,
c_re DECIMAL (10, 8),
c_im DECIMAL (10, 8),
z_re DECIMAL (10, 8) DEFAULT 0,
z_im DECIMAL (10, 8) DEFAULT 0,
znew_re DECIMAL (10, 8) DEFAULT 0,
znew_im DECIMAL (10, 8) DEFAULT 0,
steps INT DEFAULT 0,
active BIT DEFAULT 1,
)
-- Store all the c_re, c_im corresponding to each point in the plot area
-- Generate 640,000 rows (800 X 800)
INSERT INTO dbo.mandelbrot_set (a, b, c_re, c_im, steps)
SELECT a.n as a, b.n as b
,(@r_min + (a.n * @r_step)) AS c_re
,(@i_min + (b.n * @i_step)) AS c_im
,@iter AS steps
FROM
(
SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @width
) as a
CROSS JOIN
(
SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @height
) as b;
-- Iteration
WHILE (@iter > 1)
BEGIN
UPDATE dbo.mandelbrot_set
SET
znew_re = POWER(z_re,2)-POWER(z_im,2)+c_re,
znew_im = 2*z_re*z_im+c_im,
steps = steps-1
WHERE active=1;
UPDATE dbo.mandelbrot_set
SET
z_re=znew_re,
z_im=znew_im,
active= CASE
WHEN POWER(znew_re,2)+POWER(znew_im,2)>4 THEN 0
ELSE 1
END
WHERE active=1;
SET @iter = @iter - 1;
END
-- Generating PPM File
-- Save the below query results to a file with extension .ppm
-- NOTE : All the unwanted info like 'rows affected', 'completed time' etc. needs to be
-- removed from the file. Most of the image editing softwares and online viewers can display the .ppm file
SELECT 'P3' UNION ALL
SELECT CAST(@width AS VARCHAR(5)) + ' ' + CAST(@height AS VARCHAR(5)) UNION ALL
SELECT '255' UNION ALL
SELECT
STRING_AGG(CAST(CASE WHEN active = 1 THEN 0 ELSE 55 + steps % 200 END AS VARCHAR(10)) + ' ' -- R
+ CAST(CASE WHEN active = 1 THEN 0 ELSE 55+POWER(steps,3) % 200 END AS VARCHAR(10)) + ' ' -- G
+ CAST(CASE WHEN active = 1 THEN 0 ELSE 55+ POWER(steps,2) % 200 END AS VARCHAR(10)) -- B
, ' ') WITHIN GROUP (ORDER BY c_re, c_im)
FROM dbo.mandelbrot_set
GROUP BY c_re, c_im;
</syntaxhighlight>
'''OUTPUT'''
[[File:Mandelbrot set transact-sql.png|thumb]]
=={{header|TXR}}==
Line 10,177 ⟶ 13,394:
Creates same <code>mandelbrot.pgm</code> file.
<
(defvar y-centre 0.0)
(defvar width 4.0)
Line 10,252 ⟶ 13,469:
(put-line "" *stdout*))))
(plot)</
=={{header|uBasic/4tH}}==
uBasic does not support floating point calculations, so fixed point arithmetic is used, with Value 10000 representing 1.0. The Mandelbrot image is drawn using ASCII characters 1-9 to show number of iterations. Iteration count 10 or more is represented with '@'. To compensate the aspect ratio of
the font, step sizes in x and y directions are different.
<syntaxhighlight lang="basic">A =-21000 ' Left Edge = -2.1
B = 15000 ' Right Edge = 1.5
C = 15000 ' Top Edge = 1.5
Line 10,302 ⟶ 13,519:
56 Print "8"; : Return
57 Print "9"; : Return
64 Print "@"; : Return</
Output:
<pre>1111111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222211111
Line 10,350 ⟶ 13,567:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell|4}}
<syntaxhighlight lang="bash">function mandelbrot() {
local -ir maxiter=100
local -i i j {x,y}m{in,ax} d{x,y}
local -ra C=( {0..9} )
local -i lC=${#C[*]}
local -i columns=${COLUMNS:-72} lines=${LINES:-24}
((
xmin=-21*4096/10,
xmax= 7*4096/10,
ymin=-12*4096/10,
ymax= 12*4096/10,
))
for ((cy=ymax, i=0; i<lines; cy-=dy, i++))
do for ((cx=xmin, j=0; j<columns; cx+=dx, j++))
do (( x=0, y=0, x2=0, y2=0 ))
for (( iter=0; iter<maxiter && x2+y2<=16384; iter++ ))
do
((
y=((x*y)>>11)+cy,
x=x2-y2+cx,
x2=(x*x)>>12,
y2=(y*y)>>12
))
((c=iter%lC))
echo -n "${C[c]}"
done
echo
done
}</syntaxhighlight>
{{out}}
Line 10,404 ⟶ 13,632:
1111111111111222222222222333333333333333333333333333333333222222222222222
</pre>
=={{header|Vala}}==
<syntaxhighlight lang="vala">public class Example: Gtk.Application {
private Gtk.ApplicationWindow window;
private Gtk.DrawingArea drawing_area;
public Example() {
Object(application_id: "my.application", flags: ApplicationFlags.FLAGS_NONE);
this.activate.connect(() => {
window = new Gtk.ApplicationWindow(this);
drawing_area = new Gtk.DrawingArea();
drawing_area.set_draw_func(draw_mandelbrot);
window.set_child(drawing_area);
window.present();
});
}
private void draw_mandelbrot(Gtk.DrawingArea area, Cairo.Context cr, int width, int height) {
cr.set_source_rgb(0, 0, 0);
cr.paint();
int x0 = -1;
double x_increment = 2.47 / (float) width;
double y_increment = 2.24 / (float) height;
for (double x = -2.0; x < 0.47; x += x_increment, x0++) {
int y0 = -1;
for (double y = -1.12; y < 1.12; y += y_increment, y0++) {
double c_re = x;
double c_im = y;
double x_ = 0,
y_ = 0;
int iterations = 0;
int max_iterations = 50;
while (iterations < max_iterations && x_ * x_ + y_ * y_ <= 4.0) {
double x_new = x_ * x_ - y_ * y_ + c_re;
y_ = 2.0 * x_ * y_ + c_im;
x_ = x_new;
iterations++;
}
if (iterations < max_iterations) {
cr.set_source_rgb((float) iterations / (float) max_iterations, 0, 0);
cr.rectangle(x0, y0, 1, 1);
cr.fill();
}
}
}
}
public static int main(string[] argv) {
var app = new Example();
return app.run(argv);
}
}</syntaxhighlight>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
option explicit
' Raster graphics class in VBSCRIPT by Antoni Gual
'--------------------------------------------
' An array keeps the image allowing to set pixels, draw lines and boxes in it.
' at class destroy a bmp file is saved to disk and the default viewer is called
' The class can work with 8 and 24 bit bmp. With 8 bit uses a built-in palette or can import a custom one
'Declaration :
' Set MyObj = (New ImgClass)(name,width,height, orient,bits_per_pixel,palette_array)
' name:path and name of the file created
' width, height of the canvas
' orient is the way the coord increases, 1 to 4 think of the 4 cuadrants of the caterian plane
' 1 X:l>r Y:b>t 2 X:r>l Y:b>t 3 X:r>l Y:t>b 4 X:l>r Y:t>b
' bits_per_pixel can bs only 8 and 24
' palette array only to substitute the default palette for 8 bits, else put a 0
' it sets the origin at the corner of the image (bottom left if orient=1)
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray() 'rgb in 24 bit mode, indexes to palette in 8 bits
private filename
private Palette,szpal
Public Property Let depth (x)
if depth=8 or depth =24 then
Imgdepth=depth
else
Imgdepth=8
end if
bytepix=imgdepth/8
end property
Public Property Let Pixel (x,y,color)
If (x>=ImgL) or x<0 then exit property
if y>=ImgH or y<0 then exit property
ImgArray(x,y)=Color
End Property
Public Property Get Pixel (x,y)
If (x<ImgL) And (x>=0) And (y<ImgH) And (y>=0) Then
Pixel=ImgArray(x,y)
End If
End Property
Public Property Get ImgWidth ()
ImgWidth=ImgL-1
End Property
Public Property Get ImgHeight ()
ImgHeight=ImgH-1
End Property
'constructor (fn,w*2,h*2,32,0,0)
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
'offx, offy posicion de 0,0. si ofx+ , x se incrementa de izq a der, si offy+ y se incrementa de abajo arriba
dim i,j
ImgL=w
ImgH=h
tt=timer
set0 0,0 'origin blc positive up and right
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
'load user palette if provided
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
'Default palette recycled from ATARI
End if
End Sub
public sub set0 (x0,y0) 'origin can be changed during drawing
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Private Sub Class_Terminate
if err <>0 then wscript.echo "Error " & err.number
wscript.echo "writing bmp to file"
savebmp
wscript.echo "opening " & filename
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " seconds"
End Sub
'writes a 32bit integr value as binary to an utf16 string
function long2wstr( x) 'falta muy poco!!!
dim k1,k2,x1
k1= (x and &hffff&)' or (&H8000& And ((X And &h8000&)<>0)))
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
'Save the picture to a bmp file
Dim s,ostream, x,y,loc
const hdrs=54 '14+40
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) 'bitmap size including padding
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream") 'auxiliary ostream, it creates an UNICODE with bom stream in memory
.Charset = "UTF-16LE" 'o "UTF16-BE"
.Type = 2' adTypeText
.open
'build a header
'bmp header: VBSCript does'nt have records nor writes binary values to files, so we use strings of unicode chars!!
'BMP header
.writetext ChrW(&h4d42) ' 0 "BM" 4d42
.writetext long2wstr(hdrs+palsize+bms) ' 2 fiesize
.writetext long2wstr(0) ' 6 reserved
.writetext long2wstr (hdrs+palsize) '10 image offset
'InfoHeader
.writetext long2wstr(40) '14 infoheader size
.writetext long2wstr(Imgl) '18 image length
.writetext long2wstr(imgh) '22 image width
.writetext int2wstr(1) '26 planes
.writetext int2wstr(imgdepth) '28 clr depth (bpp)
.writetext long2wstr(&H0) '30 compression used 0= NOCOMPR
.writetext long2wstr(bms) '34 imgsize
.writetext long2wstr(&Hc4e) '38 bpp hor
.writetext long2wstr(&hc43) '42 bpp vert
.writetext long2wstr(szpal) '46 colors in palette
.writetext long2wstr(&H0) '50 important clrs 0=all
'write bitmap
'precalc data for orientation
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
'writelong fic, Pixel(x,y)
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
'palette
For x=0 to szpal-1
.writetext long2wstr(palette(x)) '52
Next
'image
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
'line padding
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
'use a second stream to save to file starting past the BOM the first ADODB.Stream has added
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1 ' adTypeBinary
outf.Open
.position=2 'remove bom (1 wchar)
.CopyTo outf
.close
outf.savetofile filename,2 'adSaveCreateOverWrite
outf.close
end with
End Sub
End Class
function mandelpx(x0,y0,maxit)
dim x,y,xt,i,x2,y2
i=0:x2=0:y2=0
Do While i< maxit
i=i+1
xt=x2-y2+x0
y=2*x*y+y0
x=xt
x2=x*x:y2=y*y
If (x2+y2)>=4 Then Exit do
loop
if i=maxit then
mandelpx=0
else
mandelpx = i
end if
end function
Sub domandel(x1,x2,y1,y2)
Dim i,ii,j,jj,pix,xi,yi,ym
ym=X.ImgHeight\2
'get increments in the mandel plane
xi=Abs((x1-x2)/X.ImgWidth)
yi=Abs((y2-0)/(X.ImgHeight\2))
j=0
For jj=0. To y2 Step yi
i=0
For ii=x1 To x2 Step xi
pix=mandelpx(ii,jj,256)
'use simmetry
X.imgarray(i,ym-j)=pix
X.imgarray(i,ym+j)=pix
i=i+1
Next
j=j+1
next
End Sub
'main------------------------------------
Dim i,x
'custom palette
dim pp(255)
for i=1 to 255
pp(i)=rgb(0,0,255*(i/255)^.25) 'VBS' RGB function is for the web, it's bgr for Windows BMP !!
next
dim fn:fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\mandel.bmp"
Set X = (New ImgClass)(fn,580,480,1,8,0,pp)
domandel -2.,1.,-1.2,1.2
Set X = Nothing
</syntaxhighlight>
{{out}}
[[File:Mandelbrot vbs.png]]
=={{header|Vedit macro language}}==
Line 10,409 ⟶ 13,957:
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 10,442 ⟶ 13,990:
}
BOF
</syntaxhighlight>
{{out}}
<small>
Line 10,488 ⟶ 14,036:
</pre>
</small>
=={{header|V (Vlang)}}==
Graphical
<syntaxhighlight lang="Go">
// updates and contributors at: github.com/vlang/v/blob/master/examples/gg/mandelbrot.v
// graphics are moveable by keyboard or mouse and resizable with window
import gg
import gx
import runtime
import time
const (
pwidth = 800
pheight = 600
chunk_height = 2 // image recalculated in chunks, each chunk processed in separate thread
zoom_factor = 1.1
max_iterations = 255
)
struct ViewRect {
mut:
x_min f64
x_max f64
y_min f64
y_max f64
}
fn (v &ViewRect) width() f64 {
return v.x_max - v.x_min
}
fn (v &ViewRect) height() f64 {
return v.y_max - v.y_min
}
struct AppState {
mut:
gg &gg.Context = unsafe { nil }
iidx int
pixels &u32 = unsafe { vcalloc(pwidth * pheight * sizeof(u32)) }
npixels &u32 = unsafe { vcalloc(pwidth * pheight * sizeof(u32)) } // drawings here, results swapped at the end
view ViewRect = ViewRect{-3.0773593290970673, 1.4952456603855397, -2.019938598189011, 2.3106642054225945}
scale int = 1
ntasks int = runtime.nr_jobs()
}
const colors = [gx.black, gx.blue, gx.red, gx.green, gx.yellow, gx.orange, gx.purple, gx.white,
gx.indigo, gx.violet, gx.black, gx.blue, gx.orange, gx.yellow, gx.green].map(u32(it.abgr8()))
struct MandelChunk {
cview ViewRect
ymin f64
ymax f64
}
fn (mut state AppState) update() {
mut chunk_channel := chan MandelChunk{cap: state.ntasks}
mut chunk_ready_channel := chan bool{cap: 1000}
mut threads := []thread{cap: state.ntasks}
defer {
chunk_channel.close()
threads.wait()
}
for t in 0 .. state.ntasks {
threads << spawn state.worker(t, chunk_channel, chunk_ready_channel)
}
//
mut oview := ViewRect{}
mut sw := time.new_stopwatch()
for {
sw.restart()
cview := state.view
if oview == cview {
time.sleep(5 * time.millisecond)
continue
}
// schedule chunks, describing the work:
mut nchunks := 0
for start := 0; start < pheight; start += chunk_height {
chunk_channel <- MandelChunk{
cview: cview
ymin: start
ymax: start + chunk_height
}
nchunks++
}
// wait for all chunks to be processed:
for _ in 0 .. nchunks {
_ := <-chunk_ready_channel
}
// everything is done, swap the buffer pointers
state.pixels, state.npixels = state.npixels, state.pixels
println('${state.ntasks:2} threads; ${sw.elapsed().milliseconds():3} ms / frame; scale: ${state.scale:4}')
oview = cview
}
}
[direct_array_access]
fn (mut state AppState) worker(id int, input chan MandelChunk, ready chan bool) {
for {
chunk := <-input or { break }
yscale := chunk.cview.height() / pheight
xscale := chunk.cview.width() / pwidth
mut x, mut y, mut iter := 0.0, 0.0, 0
mut y0 := chunk.ymin * yscale + chunk.cview.y_min
mut x0 := chunk.cview.x_min
for y_pixel := chunk.ymin; y_pixel < chunk.ymax && y_pixel < pheight; y_pixel++ {
yrow := unsafe { &state.npixels[int(y_pixel * pwidth)] }
y0 += yscale
x0 = chunk.cview.x_min
for x_pixel := 0; x_pixel < pwidth; x_pixel++ {
x0 += xscale
x, y = x0, y0
for iter = 0; iter < max_iterations; iter++ {
x, y = x * x - y * y + x0, 2 * x * y + y0
if x * x + y * y > 4 {
break
}
}
unsafe {
yrow[x_pixel] = colors[iter & 15]
}
}
}
ready <- true
}
}
fn (mut state AppState) draw() {
mut istream_image := state.gg.get_cached_image_by_idx(state.iidx)
istream_image.update_pixel_data(unsafe { &u8(state.pixels) })
size := gg.window_size()
state.gg.draw_image(0, 0, size.width, size.height, istream_image)
}
fn (mut state AppState) zoom(zoom_factor f64) {
c_x, c_y := (state.view.x_max + state.view.x_min) / 2, (state.view.y_max + state.view.y_min) / 2
d_x, d_y := c_x - state.view.x_min, c_y - state.view.y_min
state.view.x_min = c_x - zoom_factor * d_x
state.view.x_max = c_x + zoom_factor * d_x
state.view.y_min = c_y - zoom_factor * d_y
state.view.y_max = c_y + zoom_factor * d_y
state.scale += if zoom_factor < 1 { 1 } else { -1 }
}
fn (mut state AppState) center(s_x f64, s_y f64) {
c_x, c_y := (state.view.x_max + state.view.x_min) / 2, (state.view.y_max + state.view.y_min) / 2
d_x, d_y := c_x - state.view.x_min, c_y - state.view.y_min
state.view.x_min = s_x - d_x
state.view.x_max = s_x + d_x
state.view.y_min = s_y - d_y
state.view.y_max = s_y + d_y
}
// gg callbacks:
fn graphics_init(mut state AppState) {
state.iidx = state.gg.new_streaming_image(pwidth, pheight, 4, pixel_format: .rgba8)
}
fn graphics_frame(mut state AppState) {
state.gg.begin()
state.draw()
state.gg.end()
}
fn graphics_click(x f32, y f32, btn gg.MouseButton, mut state AppState) {
if btn == .right {
size := gg.window_size()
m_x := (x / size.width) * state.view.width() + state.view.x_min
m_y := (y / size.height) * state.view.height() + state.view.y_min
state.center(m_x, m_y)
}
}
fn graphics_move(x f32, y f32, mut state AppState) {
if state.gg.mouse_buttons.has(.left) {
size := gg.window_size()
d_x := (f64(state.gg.mouse_dx) / size.width) * state.view.width()
d_y := (f64(state.gg.mouse_dy) / size.height) * state.view.height()
state.view.x_min -= d_x
state.view.x_max -= d_x
state.view.y_min -= d_y
state.view.y_max -= d_y
}
}
fn graphics_scroll(e &gg.Event, mut state AppState) {
state.zoom(if e.scroll_y < 0 { zoom_factor } else { 1 / zoom_factor })
}
fn graphics_keydown(code gg.KeyCode, mod gg.Modifier, mut state AppState) {
s_x := state.view.width() / 5
s_y := state.view.height() / 5
// movement
mut d_x, mut d_y := 0.0, 0.0
if code == .enter {
println('> ViewRect{${state.view.x_min}, ${state.view.x_max}, ${state.view.y_min}, ${state.view.y_max}}')
}
if state.gg.pressed_keys[int(gg.KeyCode.left)] {
d_x -= s_x
}
if state.gg.pressed_keys[int(gg.KeyCode.right)] {
d_x += s_x
}
if state.gg.pressed_keys[int(gg.KeyCode.up)] {
d_y -= s_y
}
if state.gg.pressed_keys[int(gg.KeyCode.down)] {
d_y += s_y
}
state.view.x_min += d_x
state.view.x_max += d_x
state.view.y_min += d_y
state.view.y_max += d_y
// zoom in/out
if state.gg.pressed_keys[int(gg.KeyCode.left_bracket)]
|| state.gg.pressed_keys[int(gg.KeyCode.z)] {
state.zoom(1 / zoom_factor)
return
}
if state.gg.pressed_keys[int(gg.KeyCode.right_bracket)]
|| state.gg.pressed_keys[int(gg.KeyCode.x)] {
state.zoom(zoom_factor)
return
}
}
fn main() {
mut state := &AppState{}
state.gg = gg.new_context(
width: 800
height: 600
create_window: true
window_title: 'The Mandelbrot Set'
init_fn: graphics_init
frame_fn: graphics_frame
click_fn: graphics_click
move_fn: graphics_move
keydown_fn: graphics_keydown
scroll_fn: graphics_scroll
user_data: state
)
spawn state.update()
state.gg.run()
}
</syntaxhighlight>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
<
import "dome" for Window
Line 10,536 ⟶ 14,331:
}
var Game = MandelbrotSet.new(800, 600)</
{{out}}
[[File:Wren-Mandelbrot_set.png|400px]]
=={{header|XPL0}}==
<
int X, Y, \screen coordinates of current point
Cnt; \iteration counter
Line 10,564 ⟶ 14,362:
X:= ChIn(1); \wait for keystroke
SetVid($03); \restore normal text display
]</
{{out}}
[[File:MandelXPL0.png]]
Line 10,574 ⟶ 14,372:
{{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 10,670 ⟶ 14,468:
</xsl:stylesheet>
</syntaxhighlight>
=={{header|Z80 Assembly}}==
<syntaxhighlight lang="z80">
;
; Compute a Mandelbrot set on a simple Z80 computer.
Line 10,914 ⟶ 14,712:
ld d, a
ret
</syntaxhighlight>
{{out}}
<pre>
Line 10,946 ⟶ 14,744:
{{trans|XPL0}}
[[File:Mandelbrot.zkl.jpg|300px|thumb|right]]
<
bitmap:=PPM(640,480);
foreach y,x in ([0..479],[0..639]){
Line 10,965 ⟶ 14,763:
}
bitmap.write(File("foo.ppm","wb"));
}();</
|