Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

I always used a Mandelbrot image as the 'graphical' version of Hello World in any graphical application I got my hands on. Now it's your guys' turn.

  • Language must be capable of graphical output or drawing charts (saving files disallowed)
  • Render a square image or graph. The size at least 128 and at most 640 across*
  • The fractal coordinates range from approximately -2-2i to 2+2i
  • The pixels outside of the Mandelbrot set should be colored according to the number of iterations before the magnitude exceeds 2 (excluding* black & white)
  • Each iteration count must have a unique color*, and neighboring colors should preferably be easily distinguishable by the eye
  • The other pixels (presumably inside the Mandelbrot set) must be colored either black or white
  • At least 99 iterations
  • ASCII art not allowed

*) unless limited by the platform, e.g. graphical calculator

Allowed:
Allowed
Disallowed:
Disallowed
(shrunken images)

Winning conditions:
Shortest version (size in bytes) for each language will get a mention in this post, ordered by size.
No answer will ever be 'accepted' with the button.

Current ranking (2014-05-30 06:59 GMT):

share|improve this question
6  
"Easily distinguished by the eye" is hard to make objective. ...Also, apart from your personal association of the two, the Mandelbrot set has nothing to do with Hello World, so it's best to omit that from the title unless you are deliberately trolling the search engines. –  Jonathan Van Matre Mar 7 at 21:50
1  
Related: ASCII Mandelbrot (although some of the answers posted there aren't ASCII and could probably fit better as answers to this question). –  Peter Taylor Mar 7 at 22:44
2  
I've seen a few people now mentioning that they render the Mandelbrot as a "Hello World". I've done that too, for something like 30 years. The Mandelbrot is the perfect "Hello World" because it shows both that you have pixel access to the display and gives a good feel for compute bound performance on the new platform. –  Roger Dahl Mar 9 at 2:00
4  
Great idea to ask a question which requires a combination of mathematical and aesthetic sensitivities, then impose all the the design decisions in advance. –  jwg Mar 10 at 8:25
1  
Anyone manages to make one in brainfuck WINS, I'd say :D –  MadTux Mar 10 at 18:45
show 6 more comments

27 Answers 27

Sharp EL-9300 Graphics Calculator, 296 bytes

This was my secondary school graphing calculator, getting on for 20 years ago! I remember writing a mandelbrot generator for it way back then. And sure enough, its still sitting there in the NV memory:

ClrG
DispG
Range -2.35,2.35,.5,-1.55,1.55,0.5
y=-1.55
Label ly
x=-2.35
Label lx
n=1
zx=0
zy=0
Label ln
tzx=zx²-zy²+x
zy=(2*zx*zy)+y
zx=tzx
If zx²+zy²>4Goto esc
n=n+1
If n<20Goto ln
Label esc
If fpart (n/2)=0Goto npl
Plot x,y
Label npl
x=x+.05
If x<=2.35Goto lx
y=y+.05
If y<=1.55Goto ly
Wait

It took about 90 minutes to render.

This is totally ungolfed. I'm sure I could save a bit of space, but I just wanted to share this historical curiosity!

I love that the only control statements available are gotos.

Here's a photo. I don't have any other means to get the graphical output out: enter image description here

share|improve this answer
    
Me too, but my NV memory went blank after years of shelf-time. –  Mark Jeronimus Mar 8 at 9:10
1  
zx²+zy²>4 couldn't that be Abs(x)>2? –  Mark Jeronimus Mar 8 at 9:31
8  
Interesting. So you've been a nerd for quite a while. –  devnull Mar 9 at 3:34
1  
Nice "Screenshot" –  meawoppl Mar 9 at 10:01
1  
@alexy13 OP made an exception for languages that had monochrome output and mentioned calculators as an example. –  Sylwester Mar 9 at 18:08
show 8 more comments

I came across this the other day. I don't take credit for it, but damn, is it awesome:

Python:

_                                      =   (
                                        255,
                                      lambda
                               V       ,B,c
                             :c   and Y(V*V+B,B,  c
                               -1)if(abs(V)<6)else
               (              2+c-4*abs(V)**-0.4)/i
                 )  ;v,      x=1500,1000;C=range(v*x
                  );import  struct;P=struct.pack;M,\
            j  ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
            i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                  *i-950*T  **99,T*70-880*T**18+701*
                 T  **9     ,T*i**(1-T**45*2)))(sum(
               [              Y(0,(A%3/3.+X%v+(X/v+
                               A/3/3.-x/2)/1j)*2.5
                             /x   -2.7,i)**2 for  \
                               A       in C
                                      [:9]])
                                        /9)
                                       )   )

enter image description here http://preshing.com/20110926/high-resolution-mandelbrot-in-obfuscated-python/

share|improve this answer
6  
Seems to be disallowed: the regions are not easily distinguishable, or even at all. –  primo Mar 8 at 13:32
3  
Also, this writes to a file. –  Lie Ryan Mar 8 at 21:49
18  
disallowed or not, this is pretty awesome :D –  Navin Mar 9 at 2:28
4  
+1 for the most beautiful output –  DigitalTrauma Mar 9 at 4:05
8  
@DigitalTrauma, heck, +1 for most beautiful input! –  Brian S Mar 10 at 15:26
show 3 more comments

LaTeX, 673 bytes

\countdef\!1\!129\documentclass{article}\usepackage[margin=0pt,papersize=\!bp]{geometry}\usepackage{xcolor,pgf}\topskip0pt\offinterlineskip\def~{99}\let\rangeHsb~\countdef\c2\countdef\d3\countdef\e4\begin{document}\let\a\advance\let\p\pgfmathsetmacro\makeatletter\def\x#1#2#3{#10
\@whilenum#1<#2\do{#3\a#11}}\d0\x\c{\numexpr~+1}{\expandafter\edef\csname\the\c\endcsname{\hbox{\noexpand\color[Hsb]{\the\d,1,1}\/}}\a\d23
\ifnum\d>~\a\d-~\fi}\def\/{\rule{1bp}{1bp}}\x\c\!{\hbox{\x\d\!{\p\k{4*\d/(\!-1)-2}\p\K{2-4*\c/(\!-1)}\def\z{0}\def\Z{0}\x\e~{\p\:{\z*\z-\Z*\Z+\k}\p\Z{2*\z*\Z+\K}\let\z\:\p\:{\z*\z+\Z*\Z}\ifdim\:pt>4pt\csname\the\e\endcsname\e~\fi}\ifnum\e=~\/\fi}}}\stop

Result 129x129 (129 × 129)

The PDF image consists of colored square units with size 1bp × 1bp.

Ungolfed

% count register \size contains the width and height of the square
\countdef\size=1
\size=31
\documentclass{article}
\usepackage[margin=0pt,papersize=\size bp]{geometry}
\usepackage{xcolor,pgf}
\topskip0pt
\offinterlineskip
\def\iterations{99}
\let\rangeHsb\iterations
\countdef\c2
\countdef\d3
\countdef\e4
\begin{document}
\let\p\pgfmathsetmacro
\makeatletter
% \Loop: for (#1 = 0; #1 < #2; #1++) {#3}
\def\Loop#1#2#3{%
  #1=0
  \@whilenum#1<#2\do{#3\advance#11}%
}
\d0%
\Loop\c{\numexpr\iterations+1\relax}{%
  \expandafter\edef\csname\the\c\endcsname{%
    \hbox{\noexpand\color[Hsb]{\the\d,1,1}\noexpand\pixel}%
  }%
  \advance\d23 \ifnum\d>\iterations\advance\d-\iterations\fi
}
\def\pixel{\rule{1bp}{1bp}}
% \c: row
% \d: column
% \e: iteration
\Loop\c\size{%
  \typeout{c: \the\c}%
  \hbox{%
    \Loop\d\size{%
      \pgfmathsetmacro\k@re{4*\d/(\size-1)-2}%
      \pgfmathsetmacro\K@im{2-4*\c/(\size-1)}%
      \def\z@re{0}%
      \def\Z@im{0}%
      \Loop\e\iterations{%
         % calculate z(n+1) = z^2(n) + k
         \pgfmathsetmacro\temp{\z@re*\z@re-\Z@im*\Z@im+\k@re}%
         \pgfmathsetmacro\Z@im{2*\z@re*\Z@im+\K@im}%
         \let\z@re\temp
         % calculate abs(z)^2
         \pgfmathsetmacro\temp{\z@re*\z@re+\Z@im*\Z@im}%
         \ifdim\temp pt>4pt\csname\the\e\endcsname\e\iterations\fi
      }%   
      \ifnum\e=\iterations\pixel\fi
    }%
  }%
}
\stop
share|improve this answer
add comment

x86 DOS Assembly - 208 177 173

The full binary, in HEX, that I created by hand, is:

DBE3BE00A0B81300CD1056BA640007BF87F9FDBDC7008BCDE81A008AC3AA4979F7B9C70083EF784D79EE33C0CD16B80300CD10CD208BC12BC289441CDF441CDF06A701DEF9D95C088BC52BC289441CDF441CDF06A701DEF9D95C0CD9EED914D95404D95410D95C14B301D904D84C04DE0EA901D8440CD95404D94410D86414D84408D914D80CD95C10D84C04D95414D84410DF06AB01DED99BDFE09B9E7207433ADA72C632DBC3320002000400

The sample image is:

Mandlebrot screen shot with black cropped

The full source in readable ASM is fairly long (I used this to figure out how I was coding this sucker):

.286
CODE SEGMENT
ASSUME CS:code, DS:code
ORG 0100h

; *****************************************************************************
start:
  ; Mandlebrot coordinates
  zr   = DWORD PTR [SI+0]
  zi   = DWORD PTR [SI+4]
  cr   = DWORD PTR [SI+8]
  ci   = DWORD PTR [SI+12]
  zrsq = DWORD PTR [SI+16]
  zisq = DWORD PTR [SI+20]

  ; Temp int
  Temp = WORD PTR  [SI+28]

  ; ===========================================================================
  ; Initialize

  ; Initialize the FPU
  FNINIT

  ; SI points to our memory
  mov si, 0A000h ; So we can push it

  ; Shave off some bytes by reusing 100
  mov dx, 100

  ; Switch to MCGA
  mov ax, 013h
  int 010h

  ; ES:DI is the end of our drawing area
  push si
  pop es
  mov di, 63879
  std ; We're using stosb backwards

  ; Initialize our X and Y
  mov bp, 199
  mov cx, bp


  ; ===========================================================================
  ; Main draw loop

MainLoop:
  ; Get our next mandelbrot value
  call GMV

  ; Store it
  mov al, bl
  stosb

  ; Decrement our X
  dec cx
  jns MainLoop

  ; Decrement our Y
  mov cx, 199
  sub di, 120
  dec bp
  jns MainLoop


  ; ===========================================================================
  ; Done

  ; Wait for a key press
  xor ax, ax
  int 016h

  ; Change back to text mode
  mov ax, 3
  int 010h

  ; Exit to DOS
  int 020h



; *****************************************************************************
; GMV: Get Mandelbrot Value
; Gets the value for the next Mandelbrot pixel
; Returns:
;   BL - The color to use
GMV:
  ; ===========================================================================
  ; Initialize

  ; cr = (x - 100) / 50;
  mov ax, cx
  sub ax, dx                  ; \
  mov Temp, ax                ;  > ST0 = Current X - 100
  FILD Temp                   ; /
  FILD Divisor                ; ST0 = 50, ST1 = Current X - 100
  FDIVP                       ; ST0 = (Current X - 100) / 50
  FSTP cr                     ; Store the result in cr

  ; ci = (y - 100) / 50;
  mov ax, bp
  sub ax, dx                  ; \
  mov Temp, ax                ;  > ST0 = Current Y - 100
  FILD Temp                   ; /
  FILD Divisor                ; ST0 = 50, ST1 = Current Y - 100
  FDIVP                       ; ST0 = (Current Y - 100) / 50
  FSTP ci                     ; Store the result in ci

  ; zr = zi = zrsq = zisq = 0;
  FLDZ
  FST zr
  FST zi
  FST zrsq
  FSTP zisq

  ; numiteration = 1;
  mov bl, 1

  ; ===========================================================================
  ; Our main loop

  ; do {
GMVLoop:

  ; zi = 2 * zr * zi + ci;
  FLD zr
  FMUL zi
  FIMUL TwoValue
  FADD ci
  FST zi ; Reusing this later

  ; zr = zrsq - zisq + cr;
  FLD zrsq
  FSUB zisq
  FADD cr
  FST zr ; Reusing this since it already is zr

  ; zrsq = zr * zr;
  ;FLD zr ; Reused from above
  FMUL zr
  FSTP zrsq

  ; zisq = zi * zi;
  ;FLD zi ; Reused from above
  FMUL zi
  FST zisq ; Reusing this for our comparison

  ; if ((zrsq + zisq) < 4)
  ;   return numiteration;
  FADD zrsq
  FILD FourValue
  FCOMPP
  FSTSW ax
  FWAIT
  sahf
  jb GMVDone

  ;} while (numiteration++ < 200);
  inc bx
  cmp bl, dl
  jb GMVLoop

  ;return 0;
  xor bl, bl

GMVDone:  
  ret
;GMV



; *****************************************************************************
; Data

; Divisor
Divisor DW 50
; Two Value
TwoValue DW 2
; 4 Value
FourValue DW 4

CODE ENDS
END start

This is designed for compiling with TASM, runs in MCGA, and waits for a keypress before ending the program. The colors are just the default MCGA palette.

EDIT: Optimized it, now it draws backwards (same image though), and saved 31 bytes!

EDIT 2: To assuage the OP, I have recreated the binary by hand. By doing so, I also shaved another 4 bytes off. I documented every single step of the process, showing all of my work so anybody can follow along if they really want to, here (warning, it's boring and very long): http://lightning.memso.com/media/perm/mandelbrot2.txt

I used a couple regex's in EditPadPro, to find all the ; Final: ... entries in the file and dump them as hex binary to a .com file. The resulting binary is what you see at the top of this post.

share|improve this answer
    
Someone had edited my response to say you can use Python to create the file (I guess if you don't have a hex editor). I don't use Python, but their method was: python.exe -c "open('mandel.exe', 'wb').write('[ Paste Hex Here ]'.decode('hex_codec'))" –  Mark Ormston Mar 9 at 8:17
1  
Machine-code doesn't count. If that counts, then any language producing byte-code or machine-code should be shorter. I count 820 after changing everything to 1-character long names. –  Mark Jeronimus Mar 10 at 6:32
1  
No. I can hand convert ASM to binary if really necessary. It will come out with the exact same 177 bytes that my assembler helped with. The resulting code can be pasted by anybody with a binary editor into a new file, saved out, 177 bytes, and it will work as expected. Apparently SO is divided on ASM submissions, so maybe you should clarify if you feel it does not count: meta.codegolf.stackexchange.com/questions/260/… –  Mark Ormston Mar 10 at 19:14
1  
I can translate Basic code to assembly code if I take the time. That doesn't make it a valid submission. Read the comment on the first post of the page you linked. I'm with @AShelly. I quote: "You should be scored on the language you write in, not your compiler's output. (Unless you really are writing in raw binary...)" –  Mark Jeronimus Mar 11 at 18:42
2  
The thing is, there is no compiler with assembly. You just use macros. Saying that it doesn't count is like saying you can't use any predefined #define statements in C. It's just time consuming to manually replace it all. –  Mark Ormston Mar 12 at 16:33
show 5 more comments

Java - 505 405 324

Just a standard calculation, with golfitude now with extra golfitude.

enter image description here

Golfed:

import java.awt.*;class M{public static void main(String[]v){new Frame(){public void paint(Graphics g){for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);}}}.show();}}

With line breaks:

import java.awt.*;
class M{
    public static void main(String[]v){
        new Frame(){
            public void paint(Graphics g){
                for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){
                    float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;
                    for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);
                }
            }
        }.show();
    }
}
share|improve this answer
    
f.setSize(n,668); - depends heavily on the used Theme, but I'll accept it. –  Mark Jeronimus Mar 8 at 9:11
    
You can drop the imports in Java because they're auto-generated anyway. –  Mark Jeronimus Mar 8 at 9:23
    
I also see double where float could be used if you tried –  Mark Jeronimus Mar 8 at 9:29
    
JFrame => Frame shaves off 2 chars. Although you can't close the window anymore. ;) –  EthanB Mar 8 at 15:01
1  
Your class do not need to be public. Further, use Java 8 to get rid of the final modifier. And you must not omit the imports in order to be a complete submission. –  Victor Mar 10 at 4:53
show 4 more comments

Javascript (ECMAScript 6) - 315 Characters

document.body.appendChild(e=document.createElement("canvas"));v=e.getContext("2d");i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(87);f(0);f(0);k[j++]=255}v.putImageData(i,0,0)

Default Output

JSFIDDLE - Requires Firefox (as the only browser to have, so far, implemented ECMAScript 6 arrow functions)

  • Change n to vary the image size (and number of iterations).
  • Change the values passed in the f(87);f(0);f(0); calls (near the end) to change the RGB colour values. (f(8);f(8);f(8); is greyscale.)

With f(8);f(23);f(87);:

enter image description here

share|improve this answer
    
Nice. d=document would save you a few more. (Also, Is there a reason for creating the canvas? Does codegolf assume a certain level of HTML available?) –  Matthew Wilcoxson Mar 10 at 15:47
add comment

Python w/ PIL - 166 bytes

import Image
d=600;i=Image.new('RGB',(d,d))
for x in range(d*d):
 z=o=x/9e4-2-x%d/150.j-2j;c=99
 while(abs(z)<2)*c:z=z*z+o;c-=1
 i.putpixel((x/d,x%d),5**8*c)
i.show()

Output (will open in the default *.bmp viewer):

share|improve this answer
1  
You can shave off 3 if you get rid of the y loop. r=range(d*d), use x/d and x%d for x and y. –  Geobits Mar 8 at 16:15
    
@Geobits the idea actually saved 10, thanks! –  primo Mar 8 at 16:28
1  
Complex types can be initialized like: c=1+2j, which I think would save you a couple characters with: z=o=x/9e4-2+(x%d/150.-2)*1j;c=99 –  meawoppl Mar 9 at 3:10
    
@meawoppl another 7 :D –  primo Mar 9 at 5:07
    
Technically disallowed: this doesn't any graphical output feature of Python itself (and Image.show() implicitly saves a temporary file). –  nneonneo Mar 9 at 5:51
show 1 more comment

Mathematica 214 191 215

Back to Black

My earlier submission did not meet the requirement to leave the inside all black (or white). This does.

m=Compile[{{c,_Complex}},Length[FixedPointList[#^2+c&,0,99,SameTest→(Abs@#>=2&)]]];
ArrayPlot[Table[m[a+I b],{b,-2,2,.01},{a,-2,2,.01}],DataRange→{{-2,2},{-2,2}},
ColorRules→{100→Black},ColorFunction→(Hue[Log[34,#]]&)]

green

share|improve this answer
    
{b, -2, 2, .01}, {a, -2, 2, .01} is shorter and closer to the rules –  Mark Jeronimus Mar 7 at 23:50
    
@MarkJeronimus Thanks. I used the suggested range for the iterating picture. –  David Carraher Mar 8 at 3:20
    
You had it almost right, then you made the inside non-black. The last frame in the GIF is black inside and an allowed answer. EDIT: and I count 195 bytes. –  Mark Jeronimus Mar 8 at 9:20
    
I missed the point about being black. The count increased because some single characters became two characters in the cut-and-paste to SE. –  David Carraher Mar 8 at 13:34
add comment

J, 73

load'viewmat'
(0,?$~99 3)viewmat+/2<|(j./~i:2j479)(+*:) ::(3:)"0^:(i.99)0

mandelbrot set

Edit, some explaining:

x (+*:) y           NB. is x + (y^2)
x (+*:) ::(3:) y    NB. returns 3 when (+*:) fails (NaNs)
j./~i:2j479         NB. a 480x480 table of complex numbers in required range
v =: (j./~i:2j479)(+*:) ::(3:)"0 ]     NB. (rewrite the above as one verb)
v z0                NB. one iteration of the mandelbrot operation (z0 = 0)
v v z0              NB. one iteration on top of the other
(v^:n) z0           NB. the result of the mandelbrot operation, after n iterations
i.99                NB. 0 1 2 3 4 ... 98
(v^:(i.99))0        NB. returns 99 tables, one for each number of iterations
2<| y               NB. returns 1 if 2 < norm(y), 0 otherwise
2<| (v^:(i.99))0    NB. 99 tables of 1s and 0s
+/...               NB. add the tables together, element by element.
NB. we now have one 480x480 table, representing how many times each element exceeded norm-2.
colors viewmat M    NB. draw table 'M' using 'colors'; 'colors' are rgb triplets for each level of 'M'.
$~99 3              NB. 99 triplets of the numbers 99,3
?$~99 3             NB. 99 random triplets in the range 0 - 98 and 0 - 2
0,?$~99 3           NB. prepend the triplet (0,0,0): black
share|improve this answer
    
+1 but would it be possible for you to explain a little how that code work? In particular i m curious to know how (where in the code) does it pick the colors? –  plannapus Mar 10 at 8:40
    
@MarkJeronimus, I can make it 70 but I kept some things for clarity. I, thus, took the liberty to ignore the LF when counting. –  Eelvex Mar 10 at 12:39
    
@plannapus, OK, added some comments. The color picking is done with (0,?$~99 3) which produces 100 rgb triplets, one for each level. Because of the randomness, you might get less than 100 triplets so some levels will have a smoother transition (but still have different colors). –  Eelvex Mar 10 at 13:07
    
@Eelvex Thanks! –  plannapus Mar 10 at 13:09
add comment

C + Allegro 4.2.2 - 248 bytes

#include<allegro.h>
x=-1,y,K=400;float a,h,c,d,k;main(i){set_gfx_mode('SAFE',K,K,allegro_init(),0);while(x++<K)
for(y=0;y<K;y++){for(a=h=i=0;a*a+h*h<4&&++i<256;k=a,a=a*a-h*h+x*0.01-2,h=2*k*h+y*0.01-2);
putpixel(screen,x,y,i);}while(1);}END_OF_MAIN()

Output:

MSet 1

share|improve this answer
    
You should mention that this is Allegro 4 (which is quite different from Allegro 5). Which exact version is this? –  Victor Mar 10 at 4:57
    
it's either 246 or 249 long –  Mark Jeronimus Mar 10 at 6:42
    
@Victor Allegro 4.2.2. –  Oberon Mar 10 at 14:34
    
@MarkJeronimus Notepad++ tells me it's 248 characters long. –  Oberon Mar 10 at 15:33
    
Notepad++ is wrong. i.imgur.com/vnRMzOj.png –  Mark Jeronimus Mar 10 at 19:27
show 2 more comments

Python with Pylab+Numpy 151 Bytes

I couldn't bear to see a non-DQ'ed Python entry, but I think I really outdid myself on this one, and I made it down to 153 characters!

import numpy as n
from pylab import*
i=99
x,y=n.mgrid[-2:2:999j,-2:2:999j]
c=r=x*1j+y
x-=x
while i:x[(abs(r)>2)&(x==0)]=i;r=r*r+c;i-=1
show(imshow(x))

Also, notably, the second to last line raises 4 distinct runtime warnings, a new personal record!

enter image description here

share|improve this answer
    
I count 152. No space is required between import and *, and not defining f at all should be shorter, unless i've misunderstood something, which is possible. You should also change it around such that 0 iterations and 1 iterations are distiguished (they're currently both grey). –  primo Mar 9 at 14:02
    
Weird. Does wc include the eof? Fixed and slightly smaller. Just a moment. –  meawoppl Mar 9 at 17:46
    
I get 151 with wc. First golf, so not sure how to score it. –  meawoppl Mar 9 at 18:01
    
I count 150, without trailing newline. Some interpreters/compilers demand one, but the python interpreter does fine without. Not sure about wc, but maybe try stat -c %s instead. Are the black upper and lower borders part of the image? –  primo Mar 9 at 18:09
    
150 here too. Besides, you sure it's 640 or less wide, and not 999? The image looks antialiased –  Mark Jeronimus Mar 10 at 6:35
show 2 more comments

BBC Basic (228 bytes)

What about languages that nobody ever heard of in code golf? Most likely could be optimized, but I'm not quite where - improvements possible. Based of http://rosettacode.org/wiki/Mandelbrot_set#BBC_BASIC, but I tried to code golf it as much as possible.

VDU23,22,300;300;8,8,8,8
ORIGIN0,300
GCOL1
FORX=0TO600STEP2
i=X/200-2
FORY=0TO300STEP2
j=Y/200
x=0
y=0
FORI=1TO128
IFx*x+y*y>4EXIT FOR
t=i+x*x-y*y
y=j+2*x*y
x=t
NEXT
COLOUR1,I*8,I*4,0
PLOTX,Y:PLOTX,-Y
NEXT
NEXT

The generated Mandelbrot set

The > symbol on image is prompt, and it's automatically generated after running the program.

share|improve this answer
    
No need to plot twice, just go with a more inefficient version. Doesn;t it support NEXT Y,X? –  Mark Jeronimus Mar 9 at 11:59
add comment

R, 199 211 characters

Old solution at 199 characters:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1)

With indentation:

r=seq(-2,2,l=500)
c=t(sapply(r,function(x)x+1i*r)) #Produces the initial imaginary number matrix
d=z=array(0,dim(c)) #empty matrices of same size as c 
a=1:25e4            #(z will store the magnitude, d the number of iterations before it reaches 2)
for(i in 1:99){     #99 iterations
    z[a]=c[a]+z[a]^2
    s=abs(z[a])<=2
    d[a[!s]]=i
    a=a[s]
    }
image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1) #Colors are randomly ordered (except for value 0)

enter image description here

Edit: Solution at 211 characters that colors the inside of the set and the outside of the first layer differently:

r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};d[a[s]]=-1;image(d,b=-1:99,c=c(1:0,sample(rainbow(98))),ax=F,asp=1)

With indentation:

r=seq(-2,2,l=500)
c=t(sapply(r,function(x)x+1i*r))
d=z=array(0,dim(c))
a=1:25e4
for(i in 1:99){
    z[a]=c[a]+z[a]^2
    s=abs(z[a])<=2
    d[a[!s]]=i
    a=a[s]
    }
d[a[s]]=-1 #Gives the inside of the set the value -1 to differenciate it from value 0.
image(d,b=-1:99,c=c(1,sample(rainbow(99))),ax=F,asp=1)

enter image description here

share|improve this answer
    
technically black on the outside is disallowed. Did you miss that or is it difficult to implement? –  Mark Jeronimus Mar 8 at 9:19
    
@MarkJeronimus both actually :) I'll try to have a look of how to do that but i m not 100% confident that I ll find a way to do that cleanly. –  plannapus Mar 8 at 9:20
    
@MarkJeronimus Done! –  plannapus Mar 8 at 9:40
1  
Second place in the hideous colors division. –  meawoppl Mar 9 at 10:02
1  
@meawoppl blame rainbow() :) –  plannapus Mar 10 at 7:23
add comment

Octave (212 136 bytes)

(Now including some ideas due to @ChrisTaylor.)

[y,x]=ndgrid(-2:.01:2);z=c=x+i*y;m=c-c;for n=0:99;m+=abs(z)<2;z=z.^2+c;end;imagesc(m);colormap([hsv(128)(1+mod(0:79:7890,128),:);0,0,0])

With whitespace:

[y,x] = ndgrid(-2:.01:2);
z = c = x + i*y;
m = c-c;
for n=0:99
    m += abs(z)<2;
    z = z.^2 + c;
end
imagesc(m)
colormap([hsv(128)(1+mod(0:79:7900,128),:);
          0,0,0])

Output:

Mandelbrot steps to abs(z)>2

To convert to Matlab, change "m+=abs(z)<2" to "m=m+(abs(z)<2)". [+3 bytes]

To make the aspect ratio 1:1, add ";axis image". [+11 bytes]

My first answer (212 bytes):

[x,y]=meshgrid(-2:.01:2);z=c=x+i*y;m=0*e(401);for n=0:99;m+=abs(z)<2;z=z.^2+c;endfor;t=[0*e(1,7);2.^[6:-1:0]];[s{1:7}]=ndgrid(num2cell(t,1){:});t=1+sum(cat(8,s{:}),8);imagesc(m);colormap([hsv(128)(t(:),:);0,0,0])
share|improve this answer
    
There's probably a shorter way to get a discontinuous colormap.... –  aschepler Mar 8 at 20:40
    
Yes, much better now. –  aschepler Mar 9 at 1:13
    
+1 nice and concise solution. But your aspect ratio is not 1:1 (cf. rule n°2: output should be square). –  plannapus Mar 10 at 7:39
    
Fixing the aspect ratio will take 11 more bytes: append ";axis image". Is that required to qualify? –  aschepler Mar 10 at 14:39
    
i think it was just me nitpicking :) , the OP doesn't seem to have a problem with it since he didn't say anything. –  plannapus Mar 11 at 7:46
add comment

GLSL - 225 bytes:

void main(){vec2 c=gl_FragCoord.xy/iResolution.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(iChannel0,v);}

Defining variables in the code (242 bytes):

uniform vec3 r;uniform sampler2D t;void main(){vec2 c=gl_FragCoord.xy/r.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(t,v);}

See it in ShaderToy

Mandelbrot Golf

This requires a suitable palette texture be loaded as iChannel0. (The colouring here is from the "random pixel" texture on ShaderToy).

share|improve this answer
    
Variable declarations should be counted too, unless they can be auto-generated from the code. (color scheme is fine if it's only available as an external setting) –  Mark Jeronimus Mar 10 at 6:40
    
@MarkJeronimus: For the ShaderToy environment, these variables are fixed. Otherwise, for standard shaders, I would have picked shorter variable names. –  nneonneo Mar 10 at 7:25
add comment

Matlab (89 bytes)

[X,Y]=ndgrid(-2:.01:2);C=X+i*Y;Z=C-C;K=Z;
for j=1:99,Z=Z.*Z+C;K=K+(abs(Z)<2);end,imagesc(K)

Output -

enter image description here

Doesn't satisfy the requirement that the inner cells must be black or white, but that can be satisfied by either (1) using imshow(K) instead of imagesc(K) (requires 1 fewer byte but needs the image processing toolbox) or (2) appending colormap hot (requires 12 more bytes).

Ungolfed version -

Z = zeros(N);
K = Z;

[X,Y]=ndgrid(-2:.01:2);
C = X+1i*Y;

for j = 1:99
  Z = Z.*Z + C;
  K(K==0 & abs(Z) > 2) = j;
end

imagesc(K)
share|improve this answer
    
Using a library is fine if it's packaged in Matlab by default and any user can guess it's being used from the code or the error messages. –  Mark Jeronimus Mar 10 at 19:19
    
Nice, you beat me. I like the C-C in place of my 0*e(401). Plus, you're not using N. And we can get a little shorter using my m+=abs(z)<2 idea in place of your K(~K&abs(Z)>2)=j. –  aschepler Mar 11 at 12:33
    
The default colormap jet and colormap hot are both incorrect though - they only have 64 distinct colors. colormap(hot(101)) doesn't look visually distinguishable to me. colormap([0,0,0;jet(100)]) is maybe acceptable but iffy. –  aschepler Mar 11 at 12:39
    
Does that work? On Octave, K=K+abs(Z)<2 means K=((K+abs(Z))<2). (So I was wrong about the one byte estimate to eliminate +=.) –  aschepler Mar 11 at 13:06
    
Ah, good point! Edited. –  Chris Taylor Mar 11 at 13:28
add comment

Java - Processing (271 bytes)

void setup(){int h=100,e=5*h,i;float d,v,w,a,b,c;size(e,e);colorMode(HSB,h);loadPixels();d=4./e;v=2;for(int x=1;x<=e;x++){v-=d;w=2;for(int y=0;y<e;){w-=d;a=b=c=0;i=-1;while(a*a+b*b<4&&++i<h){c=a*a-b*b+v;b=2*a*b+w;a=c;}pixels[e*++y-x]=color(i*9%h,h,h-i);}}updatePixels();}

Expanded:

void setup(){
  int h=100, e=5*h, i; //init of size "e", max hue "h", iterator "i"
  float d,v,w,a,b,c; //init of stepwidth "d", y-coord "v", x-coord "w", Re(z) "a", Im(z) "b", temp_a "c"
  size(e,e);
  colorMode(HSB,h);
  loadPixels();
  d = 4./e;
  v = 2;
  for(int x = 1; x <= e; x++){
    v -= d;
    w = 2;
    for(int y = 0; y < e;){
      w -= d;
      a = b = c = 0;
      i = -1;
      while(a*a + b*b < 4 && ++i < h){
        c = a*a - b*b + v;
        b = 2*a*b + w;
        a = c;
      }
      pixels[e * ++y - x] = color(i*9 % h, h, h-i);
    }
  }
  updatePixels();
}

share|improve this answer
add comment

JavaScript + HTML5 (356B)

(Note: lines ending with '//' are added here for some readability)

Performant version (375B):

<body onload='var
w,h=w=C.width=C.height=500,X=C.getContext("2d"),I=X.createImageData(w,h),D=I.data, //
y=0,f=255,T=setInterval(function(x,i,j,k,l,c,o){for(x=0;x<w;){                     //
for(i=x*4/w-2,j=y*4/h-2,k=l=0,c=f;--c&&k*k+l*l<4;)t=k*k-l*l+i,l=2*k*l+j,k=t
D[o=(y*w+x++)*4]=(c*=0xc0ffeeee)&f
D[++o]=c>>8&f
D[++o]=c>>16&f
D[++o]=f}X.putImageData(I,0,0)
++y-h||clearInterval(T)},0)'><canvas id=C>

Slow version (356B): remove the 'var' and parameters in the inner function so that the global scope is used.

Try it out: http://jsfiddle.net/neuroburn/Bc8Rh/

enter image description here

share|improve this answer
    
Forgive me if I don't understand your instructions on making the short version. –  Mark Jeronimus Mar 8 at 21:33
    
No problem. Remove var w, at the beginning, and change function(x,i,j,k,l,c,o) to function(). –  ɲeuroburɳ Mar 8 at 21:35
add comment

gnuplot 110 (105 without newlines)

Obligatory gnuplot entry. It's been done countless times but this one is from scratch (not that it's difficult). I like how gnuplot golfs its commands intrinsically :)

f(z,w,n)=abs(z)>2||!n?n:f(z*z+w,w,n-1)
se vi map
se si sq
se isos 256
sp [-2:2] [-2:2] f(0,x+y*{0,1},99) w pm

ungolfed:

f(z,w,n)=abs(z)>2||n==0?n:f(z*z+w,w,n-1)
set view map
set size square
set isosamples 256
splot [-2:2] [-2:2] f(0,x*{1,0}+y*{0,1},99) with pm3d

However, I'm DEEPLY disappointed at the entry of complex numbers. x*{1,0}+y*{0,1} must be the saddest existing way of constructing a complex number.

Oops, the image: gnuplot mandelbrot

Set isosamples higher for better resolution. We could also say unset tics and unset colorbox for a pure image, but I think this version qualifies just fine.

share|improve this answer
    
Bet it's copy/pasta from the first google hit "gnuplot mandel". For starters, *{1,0} is unity and is more like a code-bowling way of saying *1, and probably can be dropped. (untested) –  Mark Jeronimus Mar 10 at 6:26
1  
No it's not a copy-paste. It's a very straight forward formula and it wasn't even necessary to search for it. However, I did find the pages you get with that search when I was looking for a better way of initializing complex numbers (their implementation is different, well, as different as it can be in this case). Thanks for the tip about the real part, it works. Fixing. –  orion Mar 10 at 7:53
add comment

APL, 194 chars/bytes*

m←{1{⍺=99:0⋄2<|⍵:⍺⋄(⍺+1)∇c+⍵*2}c←⍵}¨⍉v∘.+0j1×v←¯2+4÷s÷⍳s←640
'F'⎕WC'Form'('Coord' 'Pixel')('Size'(s s))
'B'⎕WC'Bitmap'('CMap'(0,,⍨⍪0,15+10×⍳24))('Bits'(24⌊m))
'F.I'⎕WC'Image'(0 0)('Picture' 'B')

This is for Dyalog APL with ⎕IO ⎕ML←1 3

Most of the space is taken by API calls to show a bitmap in a window (lines 2, 3, 4)
If there was a shortcut to do it, the code would be down to 60 chars (line 1)

PLZ HELP FIND SHORTCUT KTHX

Ungolfed version (only line 1)

s←640            ⍝ size of the bitmap
v←(4×(⍳s)÷s)-2   ⍝ vector of s reals, uniform between ¯2 and 2
m←(0j1×v)∘.+v    ⍝ square matrix of complex numbers from ¯2j¯2 to 2j2
m←{              ⍝ transform each number in matrix m according to the following
  1{             ⍝   function that takes iteration counter as ⍺ and current value as ⍵
    ⍺=99: 0      ⍝     if we have done 99 iterations, return 0
    2<|⍵: ⍺      ⍝     if |⍵| > 2 return the number of iterations done
    (⍺+1)∇c+⍵*2  ⍝     otherwise, increment the iterations and recurse with the new value
  }c←⍵           ⍝   save the initial value as c
}¨m    

Screenshot:

(Freeware version run in OS X under Wine. Yes I'm cheap like that.)

screenshot

*: Dyalog has its own single byte charset, with the APL symbols mapped to the upper 128 byte values, so the entire code can be stored in 194 bytes. Every statement in this footnote is possibly true. Keep calm and carry on golfing.

share|improve this answer
add comment

Javascript, 285B

Based off my code and some improvements on MT0's code, I've got this down to 285B in colour:

document.body.appendChild(V=document.createElement('Canvas'));j=(D=(X=V.getContext('2d')).createImageData(Z=V.width=V.height=255,Z)).data;for(x=Z*Z;x--;){k=a=b=c=0;while(a*a+b*b<4&&Z>k++){c=a*a-b*b+4*(x%Z)/Z-3;b=2*a*b+4*x/(Z*Z)-2;a=c;}j[4*x]=99*k%256;j[4*x+3]=Z;}X.putImageData(D,0,0);

in action: http://jsfiddle.net/acLhe/7/

was: Coffeescript, 342B

document.body.appendChild V=document.createElement 'Canvas'
N=99
Z=V.width=V.height=400
P=[]
P.push "rgba(0,0,0,"+Math.random()*i/N+')' for i in [N..0]
X=V.getContext '2d'
for x in [0..Z]
 for y in [0..Z]
  k=a=b=0
  [a,b]=[a*a-b*b+4*x/Z-3,2*a*b+4*y/Z-2] while a*a+b*b<4 and N>k++
  X.fillStyle=P[k-1]
  X.fillRect x,y,1,1

Coffeescript is supposed to be readable :-/ see it in action: http://jsfiddle.net/acLhe/6/

Mandelbrot Coffeescript

share|improve this answer
    
OP asks for color unless your platform doesn't support color. Looks great, though, and nice concise code. Welcome to PPCG! –  Jonathan Van Matre Mar 13 at 16:45
add comment

Perl + GD, 264

$I=new GD::Image $s=499,$s;Z(0,0,0);Z(map rand 256,1..3)for
0..99;for$x(0..$s){for$y(0..$s){for($H=$K=$c=$t=0;$c++<99&&$H*$H+$K*$K<4;){sub
Z{$I->colorAllocate(@_)}($H,$K)=($H*$H-$K*$K+4*$x/$s-2,2*$H*$K+4*$y/$s-2)}use
GD;$I->setPixel($x,$y,$c<99&&$c)}}print $I->png

Mandelbrot fractal from Perl+GD

Golfed from this code

share|improve this answer
    
Nominated: most ugly color scheme. –  meawoppl Mar 9 at 9:41
add comment

Mathematica 10.0 on Raspberry Pi, 19 chars

MandelbrotSetPlot[]

MandelbrotSetPlot is a new function in Mathematica 10.0.

enter image description here

share|improve this answer
    
How convenient, that this built in function just happens to satisfy all my requirements (except location, which can be set with 13 more characters). Except this is a standard loophole. –  Mark Jeronimus Mar 30 at 10:03
1  
Code golf is generally won by specialist languages with single-character tokens, or by systems like Mathematica that have a massive number of special functions built-in. To use them is not cheating, any more than using single-character commands would be in APL. –  Michael Stern Apr 17 at 15:08
add comment

QBasic, QuickBasic, QB64 - 156 153

SCREEN 13
FOR J=0TO 191
B=J/48-2
FOR I=0TO 191
A=I/48-2
X=A
Y=B
C=0
DO
U=X*X
V=Y*Y
Y=2*X*Y+B
X=U-V+A
C=C+1
LOOP UNTIL C>247OR U+V>4
PSET(I,J),C
NEXT
NEXT

Standard DOS palette:

enter image description here

share|improve this answer
add comment

Julia

Well, better late than never:

function mandelbrot(x0,y0,side,N=800,L=55,R=3.)
    m = [0 for i=1:N,j=1:N]
    delta = side/N
    for i=1:N, j=1:N
        c = x0+delta*i+(y0+delta*j)*im
        z, h = 0+0*im, 0
        while (h<L) && (abs(z)<R)
            z = z^2+c
            h+=1
        end
        m[j,i]=h
    end
    return m
end
n=2.6
m = mandelbrot(-n/1.3,-n/2, n)
using Winston, Color
imagesc(m)
title("Mandelbrot Set")

Colormap Mod. :

function RGB_cm()
    colormap = [RGB(0,0,0) for t=1:255*5]
    rgb = [255,0,0]
    for t in 0:(255*5-1)
    c = [0, 0, 0]
    i = ifloor(t/255)
    c[(i+3)%3!=0?(i+3)%3:3] = (-1)^i
    rgb+=c
    colormap[t+1] = RGB(rgb[1],rgb[2],rgb[3])
    end
    colormap[(end-25):end] = RGB(0,0,0)
    return colormap
end
c = RGB_cm()
Winston.colormap(c)

Output:

Mandelbrot Set

share|improve this answer
    
Should I byte-count only the first program or both? –  Mark Jeronimus Mar 29 at 10:10
    
I think both, because without the color map mod the image would not satisfy the rules. –  CCP Mar 29 at 15:35
add comment

Floater, 620 pixels

A language I made up when I got inspired by my own challenge, as well as from the esoteric language Piet.

enter image description here

share|improve this answer
add comment

Perl 6: 107 characters, 108 bytes (DQ'ed)

.say for <P3 200 200 99>,map
{(+(0,* **2+$^z...*.abs>2)[^100]X*3,21,4)X%100},{@_»i X+@_}(-2,*+.02...^*>=2)

Outputs this 200x200 ppm file (converted to PNG):

Perl 6 Mandelbrot PNG

I recognize that outputting an image file goes against the rules, but I'm posting this here pending a version that is able to draw the image itself.

I originally had the colors a little prettier, and the program a few bytes shorter, but I decided there wasn't enough contrast between layers.

Dissected:

.say for <P3 200 200 99>; # Print the PPM header

# Print the results of looping over [-2-2i,2+2i],
# I.e., all the possible additions (X+)
# of -2 to 2 in 200 parts (-2,*+.02...^*>=2)
# with -2i to 2i in 200 parts (@_»i)
.say for {@_»i X+ @_}(-2, * + .02 ...^ * >= 2).map: {
    # How many iterations it takes to get to 2, up to 100,
    # Manipulated to get an R, G, and B color value
    (
      +(0, * ** 2 + $^z ... *.abs > 2)[^100]
      #  R G  B
      X* 3,21,4
    ) X% 100
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.