Barnsley fern: Difference between revisions

Content deleted Content added
Chkas (talk | contribs)
Morn (talk | contribs)
(60 intermediate revisions by 29 users not shown)
Line 25:
Starting position: x = 0, y = 0
<br><br>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
 
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
REAL r0,r4,r15,r16,r20,r22,r23,r24,r26,r28,r44,r85,r160
 
PROC Init()
ValR("0",r0)
ValR("0.04",r4)
ValR("0.15",r16)
ValR("0.16",r16)
ValR("0.2",r20)
ValR("0.22",r22)
ValR("0.23",r23)
ValR("0.24",r24)
ValR("0.26",r26)
ValR("0.28",r28)
ValR("0.44",r44)
ValR("0.85",r85)
ValR("1.6",r160)
RETURN
 
PROC Fern(REAL POINTER scale)
BYTE r
REAL x,y,xp,yp,tmp1,tmp2
INT i,ix,iy
 
RealAssign(r0,x)
RealAssign(r0,y)
 
DO
RealMult(x,scale,tmp1)
RealMult(y,scale,tmp2)
ix=Round(tmp2) ;fern is rotated to fit the screen size
iy=Round(tmp1)+85
 
IF (ix>=0) AND (ix<=319) AND (iy>=0) AND (iy<=191) THEN
Plot(ix,iy)
FI
r=Rand(100)
RealAssign(x,xp) ;xp=x
RealAssign(y,yp) ;yp=y
IF r<1 THEN
RealAssign(r0,x) ;x=0
RealMult(r16,yp,y) ;y=0.16*yp
ELSEIF r<86 THEN
RealMult(r85,xp,tmp1) ;tmp1=0.85*xp
RealMult(r4,yp,tmp2) ;tmp2=0.4*yp
RealAdd(tmp1,tmp2,x) ;x=0.85*xp+0.4*yp
 
RealMult(r4,xp,tmp1) ;tmp1=0.04*xp
RealSub(r160,tmp1,tmp2) ;tmp2=-0.04*xp+1.6
RealMult(r85,yp,tmp1) ;tmp1=0.85*yp
RealAdd(tmp1,tmp2,y) ;y=-0.04*xp+0.85*yp+1.6
ELSEIF r<93 THEN
RealMult(r20,xp,tmp1) ;tmp1=0.2*xp
RealMult(r26,yp,tmp2) ;tmp2=0.26*yp
RealSub(tmp1,tmp2,x) ;x=0.2*xp-0.26*yp
 
RealMult(r23,xp,tmp1) ;tmp1=0.23*xp
RealAdd(r160,tmp1,tmp2) ;tmp2=0.23*xp+1.6
RealMult(r22,yp,tmp1) ;tmp1=0.22*yp
RealAdd(tmp1,tmp2,y) ;y=0.23*xp+0.22*yp+1.6
ELSE
RealMult(r15,xp,tmp1) ;tmp1=0.15*xp
RealMult(r28,yp,tmp2) ;tmp2=0.28*yp
RealSub(tmp2,tmp1,x) ;x=-0.15*xp+0.28*yp
 
RealMult(r26,xp,tmp1) ;tmp1=0.26*xp
RealAdd(r44,tmp1,tmp2) ;tmp2=0.26*xp+0.44
RealMult(r24,yp,tmp1) ;tmp1=0.24*yp
RealAdd(tmp1,tmp2,y) ;y=0.26*xp+0.44*yp+0.44
FI
 
Poke(77,0) ;turn off the attract mode
UNTIL CH#$FF ;until key pressed
OD
CH=$FF
RETURN
 
PROC Main()
REAL scale
 
Graphics(8+16)
Color=1
COLOR1=$BA
COLOR2=$B2
 
Init()
ValR("30",scale)
Fern(scale)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Barnsley_fern.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|SDLAda}}
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
with SDL.Video.Windows.Makers;
Line 121 ⟶ 218:
Window.Finalize;
SDL.Finalise;
end Barnsley_Fern;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 127 ⟶ 224:
 
This program generates a [https://en.wikipedia.org/wiki/Netpbm_format PBM file].
<langsyntaxhighlight lang="algol68">
BEGIN
INT iterations = 300000;
Line 184 ⟶ 281:
leave: SKIP
END
</syntaxhighlight>
</lang>
 
=={{header|Applesoft BASIC}}==
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic> 100 LET YY(1) = .16
<syntaxhighlight lang="applesoftbasic"> 100 LET YY(1) = .16
110 XX(2) = .85:XY(2) = .04
120 YX(2) = - .04:YY(2) = .85
Line 211 ⟶ 309:
330 HPLOT X% * 2 + 1,Y%
340 NEXT
</syntaxhighlight>
</lang>
 
==={{header|BBC BASICBASIC256}}===
<syntaxhighlight lang="basic256"># adjustable window altoght
# call the subroutine with the altoght you want
# it's possible to have a window that's large than your display
call barnsley(800)
end
 
subroutine barnsley(alto)
graphsize alto / 2, alto
color rgb(0, 255, 0)
 
f = alto / 10.6
c = alto / 4 - alto / 40
x = 0 : y = 0
 
for n = 1 to alto * 50
p = rand * 100
begin case
case p <= 1
nx = 0
ny = 0.16 * y
case p <= 8
nx = 0.2 * x - 0.26 * y
ny = 0.23 * x + 0.22 * y + 1.6
case p <= 15
nx = -0.15 * x + 0.28 * y
ny = 0.26 * x + 0.24 * y + 0.44
else
nx = 0.85 * x + 0.04 * y
ny = -0.04 * x + 0.85 * y + 1.6
end case
x = nx : y = ny
plot(c + x * f, alto - y * f)
next n
 
# remove comment (#) in next line to save window as .png file
# imgsave("Barnsley_fern.png")
end subroutine</syntaxhighlight>
{{out}}
[https://www.dropbox.com/s/8rkgguj3ol57771/Barnsley_fern_BASIC256.png?dl=0 Barnsley fern BASIC256 image]
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> GCOL 2 : REM Green Graphics Color
X=0 : Y=0
FOR I%=1 TO 100000
Line 228 ⟶ 367:
PLOT 1000 + X * 130 , Y * 130
NEXT
END</langsyntaxhighlight>
==={{header|uBasic/4tH}}===
uBasic/4tH does not feature graphics or floating point, so it requires some extra code to achieve this. This version uses binary scaling.
<syntaxhighlight lang="qbasic">Dim @o(5) ' 0 = SVG file, 1 = color, 2 = fillcolor, 3 = pixel, 4 = text
 
' === Begin Program ===
 
If Info("wordsize") < 64 Then Print "This program requires a 64-bit uBasic" : End
 
Proc _SVGopen ("svgfern.svg")
Proc _Canvas (500, 768) ' light gray background
Proc _Background (FUNC(_RGBtoColor (0, 0, 0)))
Proc _SetMode ("dot") ' we want dots, not pixels
 
For i = 1 To 25000
Let r = Rnd (100)
 
If r = 1 Then
Let x = 0
Let y = FUNC (_Fmul(FUNC(_Fdiv(16, 100)) , y))
Else
 
If r < 9 Then
Let x = FUNC(_Fmul(FUNC(_Fdiv(2, 10)), x)) - FUNC(_Fmul(FUNC(_Fdiv(26, 100)), y))
Let y = FUNC(_Fmul(FUNC(_Fdiv(-23, 100)), x)) + FUNC(_Fmul(FUNC(_Fdiv(22, 100)), y)) + FUNC(_Fdiv(16, 10))
Else
 
If r < 16 then
Let x = FUNC(_Fmul(FUNC(_Fdiv(-15, 100)), x)) + FUNC(_Fmul(FUNC(_Fdiv(28, 100)), y))
Let y = FUNC(_Fmul(FUNC(_Fdiv(26, 100)), x)) + FUNC(_Fmul(FUNC(_Fdiv(24, 100)), y)) + FUNC(_Fdiv(44, 100))
Else
 
Let x = FUNC(_Fmul(FUNC(_Fdiv(85, 100)), x)) + FUNC(_Fmul(FUNC(_Fdiv(4, 100)), y))
Let y = FUNC(_Fmul(FUNC(_Fdiv(-4, 100)), x)) + FUNC(_Fmul(FUNC(_Fdiv(85, 100)), y)) + FUNC(_Fdiv(16, 10))
EndIf
EndIf
EndIf
 
Let q = FUNC(_Fround(FUNC(_Fmul(x + FUNC(_Ntof(3)), FUNC(_Ntof(70))))))
Let p = FUNC(_Fround(FUNC(_Ntof(700)) - FUNC(_Fmul(y, FUNC(_Ntof(70))))))
 
Proc _SetColor (FUNC(_RGBtoColor (0, 128 + Rnd(128), 0)))
Proc _SetPixel (p+20, q)
Next
 
Proc _SVGclose
End
 
' === End Program ===
 
_Ntof Param (1) : Return (a@*16384)
_Ftoi Param (1) : Return ((10000*a@)/16384)
_Fmul Param (2) : Return ((a@*b@)/16384)
_Fdiv Param (2) : Return ((a@*16384)/b@)
_Fround Param (1) : Return ((a@+8192)/16384)
 
_RGBtoColor Param (3) : Return (a@ * 65536 + b@ * 256 + c@)
_SetColor Param (1) : @o(1) = a@ : Return
_GetColor Return (@o(1))
_SetFill Param (1) : @o(2) = a@ : Return
_GetFill Return (@o(2))
_SetPixel Param(2) : Proc @o(3)(a@, b@) : Return
_SVGclose Write @o(0), "</svg>" : Close @o(0) : Return
_color_ Param (1) : Proc _PrintRGB (a@) : Write @o(0), "\q />" : Return
 
_PrintRGB
Param (1)
Radix 16
 
If a@ < 0 Then
Write @o(0), "none";
Else
Write @o(0), Show(Str ("#!######", a@));
EndIf
 
Radix 10
Return
 
_Background
Param (1)
 
Write @o(0), "<rect width=\q100%\q height=\q100%\q fill=\q";
Proc _color_ (a@)
Return
 
_pixel_
Param (2)
 
Write @o(0), "<rect x=\q";b@;"\q y=\q";a@;
Write @o(0), "\q width=\q1px\q height=\q1px\q fill=\q";
Proc _color_ (@o(1))
Return
 
_dot_
Param (2)
 
Write @o(0), "<circle cx=\q";b@;"\q cy=\q";a@;
Write @o(0), "\q r=\q0.5px\q fill=\q";
Proc _color_ (@o(1))
Return
 
_SetMode
Param (1)
 
If Comp(a@, "pixel") = 0 Then
@o(3) = _pixel_
Else If Comp(a@, "dot") = 0 Then
@o(3) = _dot_
Else Print "Bad mode" : Raise 1
Endif : Endif
Return
 
_Canvas
Param (2)
 
Write @o(0), "<svg width=\q";a@;"\q height=\q";b@;"\q viewBox=\q0 0 ";a@;" ";b@;
Write @o(0), "\q xmlns=\qhttp://www.w3.org/2000/svg\q ";
Write @o(0), "xmlns:xlink=\qhttp://www.w3.org/1999/xlink\q>"
Return
 
_SVGopen
Param (1)
 
If Set (@o(0), Open (a@, "w")) < 0 Then
Print "Cannot open \q";Show (a@);"\q" : Raise 1
Else
Write @o(0), "<?xml version=\q1.0\q encoding=\qUTF-8\q standalone=\qno\q?>"
Write @o(0), "<!DOCTYPE svg PUBLIC \q-//W3C//DTD SVG 1.1//EN\q ";
Write @o(0), "\qhttp://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\q>"
EndIf
Return</syntaxhighlight>
This version uses decimal fixed-point numbers. It is not only faster, but also provides a better rendition of the Barnsley fern. It uses the very same SVG routines as the version above, so these are not included.
{{Trans|Forth}}
<syntaxhighlight lang="qbasic">Dim @o(5) ' 0 = SVG file, 1 = color, 2 = fillcolor, 3 = pixel, 4 = text
Dim @c(20) ' coefficients
 
w = 400 : h = 600 : s = 17
 
Proc _coefficients
Proc _SVGopen ("svgfern.svg")
Proc _Canvas (w, h) ' light gray background
Proc _Background (FUNC(_RGBtoColor (0, 0, 0)))
Proc _SetMode ("dot") ' we want dots, not pixels
 
For i = 0 to 50000
Proc _transformation (FUNC (_randomchoice))
 
Proc _SetColor (FUNC(_RGBtoColor (0, 128 + Rnd(128), 0)))
p = h - y/s
q = w/2 + x/s
 
Proc _SetPixel (p, q)
Next
 
Proc _SVGclose
End
 
_coefficients
Local (1)
 
Push 0 , 0 , 0 , 160 , 0 ' 1% of the time - f1
Push 200 , -260 , 230 , 220 , 1600 ' 7% of the time - f3
Push -150 , 280 , 260 , 240 , 440 ' 7% of the time - f4
Push 850 , 40 , -40 , 850 , 1600 ' 85% of the time - f2
 
For a@ = 19 To 0 Step -1 : @c(a@) = Pop() : Next
Return
 
_randomchoice
Local (1)
 
Push Rnd (100)
a@ = (Tos() > 0)
a@ = a@ + (Tos () > 7)
Return ((a@ + (Pop () > 14)) * 5)
 
_transformation
Param (1)
Local (2)
 
b@ = @c(a@) * x
b@ = (b@ + @c(a@+1) * y) / 1000
 
c@ = @c(a@+2) * x
c@ = (c@ + @c(a@+3) * y) / 1000
 
x = b@ : y = @c(a@+4) + c@
Return</syntaxhighlight>
 
=={{header|C}}==
This implementation requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library. Iteration starts from (0,0) as required by the task however before plotting the point is translated and scaled as negative co-ordinates are not supported by the graphics window, scaling is necessary as otherwise the fern is tiny even for large iterations ( > 1000000).
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 295 ⟶ 621:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Diagnostics;
using System.Drawing;
Line 343 ⟶ 669:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
[[File:BFCpp.png|200px|thumb|right]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <ctime>
Line 478 ⟶ 804:
fern f; f.draw(); return 0;
}
</syntaxhighlight>
</lang>
 
===Cross-Platform Alternative===
Line 484 ⟶ 810:
This version uses the QImage class from the Qt toolkit as an easy way to save an image in PNG format.
It also uses the C++ 11 random number library. Built and tested on macOS 10.15.4 with Qt 5.12.5.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
#include <vector>
Line 541 ⟶ 867:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
[[Media:Barnsley fern cpp.png]]
See: [https://slack-files.com/T0CNUL56D-F017EKXBC0Y-ca68fe222b barnsley_fern.png] (offsite PNG image)
 
=={{header|Common Lisp}}==
{{libheader|opticl}}
This code uses the <code>opticl</code> package for generating an image and saving it as a PNG file.
<langsyntaxhighlight lang="lisp">(defpackage #:barnsley-fern
(:use #:cl
#:opticl))
Line 595 ⟶ 921:
(set-pixel image x y)
(multiple-value-setq (x y) (funcall (choose-transform) x y)))
(write-png-file filespec image)))</langsyntaxhighlight>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">define x1 = 0, y1 = 0
 
bgcolor 0, 0, 0
cls graphics
 
for i = 1 to 10000
 
let r = rnd
 
if r > 0 and r < .01 then
 
let x = .0
let y = .16 * y
 
endif
 
if r > .01 and r < .08 then
 
let x = .22 * x - .26 * y
let y = -.23 * x + .22 * y + 1.6
 
endif
 
if r > .075 and r < .15 then
 
let x = .15 * x + .28 * y
let y = -.29 * x + .24 * y + .44
 
endif
 
let x = .85 * x + .04 * y
let y = -.04 * x + .85 * y + 1.6
 
let x1 = (x + 3) * 70
let y1 = 700 - y * 70
 
fgcolor 0, int(rnd * 255), 0
 
dot x1, y1
 
wait
 
next i</syntaxhighlight>
 
=={{header|D}}==
{{trans|Raku}}
{{libheader|dlib}}
<syntaxhighlight lang="d">#!/usr/bin/env dub
/+ dub.sdl:
dependency "dlib" version="~>0.21.0"
+/
import std.random;
 
import dlib.image;
 
void main()
{
enum WIDTH = 640;
enum HEIGHT = 640;
enum ITERATIONS = 2E6;
 
float x = 0.0f;
float y = 0.0f;
 
auto rng = Random(unpredictableSeed);
auto color = Color4f(0.0f, 1.0f, 0.0f);
auto img = image(WIDTH, HEIGHT);
 
foreach (_; 0..ITERATIONS)
{
auto r = uniform(0, 101, rng);
if (r <= 1)
{
x = 0.0;
y = 0.16 * y;
}
else
{
if (r <= 8)
{
x = 0.20 * x - 0.26 * y;
y = 0.23 * x + 0.22 * y + 1.60;
}
else
{
if (r <= 15)
{
x = -0.15 * x + 0.28 * y;
y = 0.26 * x + 0.24 * y + 0.44;
}
else
{
x = 0.85 * x + 0.04 * y;
y = -0.04 * x + 0.85 * y + 1.6;
}
}
}
auto X = cast(int) (WIDTH / 2.0 + x * 60);
auto Y = HEIGHT - cast(int)(y * 60);
img[X, Y] = color;
}
img.saveImage(`barnsley_dlib.png`);
}</syntaxhighlight>
 
=={{header|Delphi}}==
{{trans|Java}}
Hint: After putting a TPaintBox on the main form align it to alClient. Client width / height of the main form should be no less than 640 x 480.
<langsyntaxhighlight lang="delphi">unit Unit1;
 
interface
Line 663 ⟶ 1,095:
end;
 
end.</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
[https://easylang.onlinedev/apps/barnsley-fern.html Run it]
 
<syntaxhighlight lang="text">
<lang>color 060
color 060
for i% range 200000
for i = 1 to 200000
r = randomf
if r < 0.01
Line 687 ⟶ 1,120:
x = nx
y = ny
move 50 + x * 15 100 - y * 10
rect 0.3 0.3
.
.</lang>
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
[[File:Barnsley fern emacs lisp.png|thumb|Output]]
<syntaxhighlight lang="lisp">; Barnsley fern
 
(defun make-array (size)
"Create an empty array with size*size elements."
(setq m-array (make-vector size nil))
(dotimes (i size)
(setf (aref m-array i) (make-vector size 0)))
m-array)
 
(defun barnsley-next (p)
"Return the next Barnsley fern coordinates."
(let ((r (random 100))
(x (car p))
(y (cdr p)))
(cond ((< r 2) (setq nx 0) (setq ny (* 0.16 y)))
((< r 9) (setq nx (- (* 0.2 x) (* 0.26 y)))
(setq ny (+ 1.6 (* 0.23 x) (* 0.22 y))))
((< r 16) (setq nx (+ (* -0.15 x) (* 0.28 y)))
(setq ny (+ 0.44 (* 0.26 x) (* 0.24 y))))
(t (setq nx (+ (* 0.85 x) (* 0.04 y)))
(setq ny (+ 1.6 (* -0.04 x) (* 0.85 y)))))
(cons nx ny)))
 
(defun barnsley-lines (arr size)
"Turn array into a string for XPM conversion."
(setq all "")
(dotimes (y size)
(setq line "")
(dotimes (x size)
(setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
(setq all (concat all "\"" line "\",\n")))
all)
 
(defun barnsley-show (arr size)
"Convert size*size array to XPM image and show it."
(insert-image (create-image (concat (format "/* XPM */
static char * barnsley[] = {
\"%i %i 2 1\",
\". c #000000\",
\"* c #00ff00\"," size size)
(barnsley-lines arr size) "};") 'xpm t)))
 
(defun barnsley (size scale max-iter)
"Plot the Barnsley fern."
(let ((arr (make-array size))
(p (cons 0 0)))
(dotimes (it max-iter)
(setq p (barnsley-next p))
(setq x (round (+ (/ size 2) (* scale (car p)))))
(setq y (round (- size (* scale (cdr p)) 1)))
(setf (elt (elt arr y) x) 1))
(barnsley-show arr size)))
 
(barnsley 400 35 100000)</syntaxhighlight>
 
=={{header|F sharp|F#}}==
 
<syntaxhighlight lang="fsharp">
open System.Drawing
 
let (|F1|F2|F3|F4|) r =
if r < 0.01 then F1
else if r < 0.08 then F3
else if r < 0.15 then F4
else F2
let barnsleyFernFunction (x, y) = function
| F1 -> (0.0, 0.16*y)
| F2 -> ((0.85*x + 0.04*y), (-0.04*x + 0.85*y + 1.6))
| F3 -> ((0.2*x - 0.26*y), (0.23*x + 0.22*y + 1.6))
| F4 -> ((-0.15*x + 0.28*y), (0.26*x + 0.24*y + 0.44))
let barnsleyFern () =
let rnd = System.Random()
(0.0, 0.0)
|> Seq.unfold (fun point -> Some (point, barnsleyFernFunction point (rnd.NextDouble())))
let run width height =
let emptyBitmap = new Bitmap(int width,int height)
let bitmap =
barnsleyFern ()
|> Seq.take 250000 // calculate points
|> Seq.map (fun (x,y) -> (int (width/2.0+(width*x/11.0)), int (height-(height*y/11.0)))) // transform to pixels
|> Seq.fold (fun (b:Bitmap) (x,y) -> b.SetPixel(x-1,y-1,Color.ForestGreen); b) emptyBitmap // add pixels to bitmap
bitmap.Save("BFFsharp.png")
</syntaxhighlight>
 
{{Out|Use}}
<syntaxhighlight lang="fsharp">
BarnsleyFern.run 720 720
</syntaxhighlight>
 
=={{header|Forth}}==
 
{{works with|gforth|0.7.3}}
{{libheader|SDL2}}
 
===Fixed Point and Matrix solution===
Traditionaly, Forth use Fixed-Point Arithmetic (here with a 1000 scale). For transformation function choice, a formula is used to pick coefficients in a matrix.
 
<syntaxhighlight lang="forth">
s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init SDL_Init n -- n
c-function sdl-quit SDL_Quit -- void
c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a
c-function sdl-createrenderer SDL_CreateRenderer a n n -- a
c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n
c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n
c-function sdl-renderpresent SDL_RenderPresent a -- void
c-function sdl-delay SDL_Delay n -- void
 
require random.fs
 
0 value window
0 value renderer
variable x
variable y
 
: initFern ( -- )
$20 sdl-init drop
s\" Rosetta Task : Barnsley fern\x0" drop 0 0 1000 1000 $0 sdl-createwindow to window
window -1 $2 sdl-createrenderer to renderer
renderer 0 255 0 255 sdl-setdrawcolor drop
;
 
create coefficients
0 , 0 , 0 , 160 , 0 , \ 1% of the time - f1
200 , -260 , 230 , 220 , 1600 , \ 7% of the time - f3
-150 , 280 , 260 , 240 , 440 , \ 7% of the time - f4
850 , 40 , -40 , 850 , 1600 , \ 85% of the time - f2
 
: nextcoeff ( n -- n+1 coeff ) coefficients over cells + @ swap 1+ swap ;
: transformation ( n -- )
nextcoeff x @ * swap nextcoeff y @ * rot + 1000 / swap
nextcoeff x @ * swap nextcoeff y @ * rot + 1000 / swap nextcoeff rot + y ! drop
x ! \ x shall be modified after y calculation
;
: randomchoice ( -- index )
100 random
dup 0 > swap
dup 7 > swap
dup 14 > swap drop
+ + negate 5 *
;
 
: fern
initFern
20000 0 do
randomchoice transformation
renderer x @ 10 / 500 + y @ 10 / sdl-drawpoint drop
loop
renderer sdl-renderpresent
5000 sdl-delay
sdl-quit
;
 
fern</syntaxhighlight>
 
===Floating Point and Multiple Functions solution===
Forth may use a dedicated Floating Point Stack. For transformation, a pointer to one of the 4 functions is used to be be called at the end of the loop.
 
<syntaxhighlight lang="forth">
s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init SDL_Init n -- n
c-function sdl-quit SDL_Quit -- void
c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a
c-function sdl-createrenderer SDL_CreateRenderer a n n -- a
c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n
c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n
c-function sdl-renderpresent SDL_RenderPresent a -- void
c-function sdl-delay SDL_Delay n -- void
 
require random.fs
 
0 value window
0 value renderer
0 value diceThrow
fvariable x
fvariable y
variable transformation
 
: initFern ( -- )
$20 sdl-init drop
s\" Rosetta Task : Barnsley fern\x0" drop 0 0 1000 1000 $0 sdl-createwindow to window
window -1 $2 sdl-createrenderer to renderer
renderer 0 255 0 255 sdl-setdrawcolor drop
;
: closeFern sdl-quit ;
 
: f1
0e0 x f!
y f@ 0.16e0 f* y f!
;
: f2
x f@ 0.85e0 f* y f@ 0.040e0 f* f+
x f@ -0.04e0 f* y f@ 0.850e0 f* f+ 1.600e0 f+ y f!
x f!
;
: f3
x f@ 0.200e0 f* y f@ -0.260e0 f* f+
x f@ 0.230e0 f* y f@ 0.220e0 f* f+ 1.600e0 f+ y f!
x f!
;
: f4
x f@ -0.150e0 f* y f@ 0.280e0 f* f+
x f@ 0.260e0 f* y f@ 0.240e0 f* f+ 0.440e0 f+ y f!
x f!
;
 
: fern
initFern
0e0 x f!
0e0 y f!
20000 0 do
renderer x f@ 50e0 f* f>s 500 + y f@ 50e0 f* f>s sdl-drawpoint drop
100 random to diceThrow
['] f2 transformation !
diceThrow 15 < if ['] f4 transformation ! then
diceThrow 8 < if ['] f3 transformation ! then
diceThrow 1 < if ['] f1 transformation ! then
transformation @ execute
loop
renderer sdl-renderpresent
5000 sdl-delay
closeFern
;
 
fern</syntaxhighlight>
 
 
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
!Generates an output file "plot.dat" that contains the x and y coordinates
!for a scatter plot that can be visualized with say, GNUPlot
Line 742 ⟶ 1,411:
close(1)
end program BarnsleyFern
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 10-10-2016
' compile with: fbc -s console
 
Line 798 ⟶ 1,467:
Windowtitle "hit any key to end program"
Sleep
End</langsyntaxhighlight>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
<lang Frink>
g = new graphics
g.backgroundColor[0,0,0] // black
Line 838 ⟶ 1,507:
 
g.show[]
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
In [{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Barnsley_fern this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Barnsley fern 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
'''Test case'''
 
[[File:Fōrmulæ - Barnsley fern 02.png]]
 
[[File:Fōrmulæ - Barnsley fern 03.png]]
 
=={{header|G'MIC}}==
<syntaxhighlight lang="c">
<lang c>
# Put this into a new file 'fern.gmic' and invoke it from the command line, like this:
# $ gmic fern.gmic -barnsley_fern
Line 872 ⟶ 1,547:
)"}
-r 40%,40%,1,1,2
</syntaxhighlight>
</lang>
 
=={{header|gnuplot}}==
Line 879 ⟶ 1,554:
[[File:BarnsleyFernGnu.png|right|thumb|Output BarnsleyFernGnu.png]]
 
<langsyntaxhighlight lang="gnuplot">
## Barnsley fern fractal 2/17/17 aev
reset
Line 904 ⟶ 1,579:
set output
unset print
</langsyntaxhighlight>
{{Output}}
<pre>
Line 912 ⟶ 1,587:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 983 ⟶ 1,658:
log.Fatal(err)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
{{libheader|JavaFX}}
 
<syntaxhighlight lang="groovy">import javafx.animation.AnimationTimer
import javafx.application.Application
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.image.ImageView
import javafx.scene.image.WritableImage
import javafx.scene.paint.Color
import javafx.stage.Stage
 
class BarnsleyFern extends Application {
 
@Override
void start(Stage primaryStage) {
primaryStage.title = 'Barnsley Fern'
primaryStage.scene = getScene()
primaryStage.show()
}
 
def getScene() {
def root = new Group()
def scene = new Scene(root, 640, 640)
def imageWriter = new WritableImage(640, 640)
def imageView = new ImageView(imageWriter)
root.children.add imageView
 
def pixelWriter = imageWriter.pixelWriter
 
def x = 0, y = 0
 
({
 
50.times {
def r = Math.random()
 
if (r <= 0.01) {
x = 0
y = 0.16 * y
} else if (r <= 0.08) {
x = 0.2 * x - 0.26 * y
y = 0.23 * x + 0.22 * y + 1.6
} else if (r <= 0.15) {
x = -0.15 * x + 0.28 * y
y = 0.26 * x + 0.24 * y + 0.44
} else {
x = 0.85 * x + 0.04 * y
y = -0.04 * x + 0.85 * y + 1.6
}
 
pixelWriter.setColor(Math.round(640 / 2 + x * 640 / 11) as Integer, Math.round(640 - y * 640 / 11) as Integer, Color.GREEN)
}
 
} as AnimationTimer).start()
 
scene
}
 
static void main(args) {
launch(BarnsleyFern)
}
}
</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (scanl')
import Diagrams.Backend.Rasterific.CmdLine
import Diagrams.Prelude
Line 1,029 ⟶ 1,770:
main = do
rand <- getStdGen
mainWith $ drawFern (randomRs (0, 1) rand)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Fern.bas"
110 RANDOMIZE
120 SET VIDEO MODE 1:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27
Line 1,053 ⟶ 1,794:
290 LET X=NX:LET Y=NY
300 PLOT X*96+600,Y*96
310 NEXT</langsyntaxhighlight>
 
=={{header|J}}==
[[File:jfern.png|200px140px|thumb|right]]
<langsyntaxhighlight lang="j">require 'plot'
f=: |: 0 ". 1 2 }. ];._2 noun define
w 0 a 0 b 0 c 0.16 d 0 0 e f 0.01 prob
f1 0.85 - 0.04 0.04 0.8516 0 1.600 0.8501
f2 0.20 85 -0.2304 -0.2604 0.2285 0 1.60 0.0785
-f3 0.1520 0.26 23 -0.2826 0.2422 0 01.4460 0.07
f4 -0.15 0.26 0.28 0.24 0 0.44 0.07
)
Line 1,072 ⟶ 1,814:
ifs=: (fa@] + fm@] +/ .* [) prob
getPoints=: ifs^:(<200000)
plotFern=: 'dot;gridsframe 0;grids 0;tics 0 0;labels 0;aspect 02;color green' plot ;/@|:
plotFern getPoints 0 0</langsyntaxhighlight>
 
=={{header|Java}}==
[[File:barnsley_fern.png|200px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
Line 1,146 ⟶ 1,888:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,152 ⟶ 1,894:
[[File:BarnsleyFernjs.png|right|thumb|Output BarnsleyFernjs.png]]
 
<langsyntaxhighlight lang="javascript">// Barnsley fern fractal
//6/17/16 aev
function pBarnsleyFern(canvasId, lim) {
Line 1,193 ⟶ 1,935:
ctx.fillRect(x * 50 + 260, -y * 50 + 540, 1, 1);
} //fend i
}</langsyntaxhighlight>
'''Executing:'''
<langsyntaxhighlight lang="html">
<html>
<head><script src="BarnsleyFern.js"></script></head>
Line 1,203 ⟶ 1,945:
</body>
</html>
</langsyntaxhighlight>
{{Output}}
<pre>
Line 1,210 ⟶ 1,952:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Images
{{works with|Julia|0.6}}
 
mutable struct BarnsleyFern
<lang julia>function barnsleyfern(n::Integer)
funs = (width::Int
height::Int
(x, y) -> (0, 0.16y),
color::RGB
(x, y) -> (0.85x + 0.04y, -0.04x + 0.85y + 1.6),
x::Float64
(x, y) -> (0.2x - 0.26y, 0.23x + 0.22y + 1.6),
y::Float64
(x, y) -> (-0.15x + 0,28y, 0.26x + 0.24y + 0.44))
rst = fern::Matrix{Float64RGB}(n, 2)
function BarnsleyFern(width, height, color = RGB(0.0, 1.0, 0.0), bgcolor = RGB(0.0, 0.0, 0.0))
rst[1, :] = 0.0
img = [bgcolor for rowx in 1:width, y in 21:nheight]
rcx = randInt(0:99floor(2.182 * (width - 1) / 4.8378) + 1)
ifcy r= <Int(floor(9.9983 1;* (height - 1) / 9.9983) f =+ 1;)
elseifimg[cx, r < 86; fcy] = 2;color
elseifreturn rnew(width, <height, 93;color, f0.0, =0.0, 3;img)
else f = 4; end
rst[row, 1], rst[row, 2] = funs[f](rst[row-1, 1], rst[row-1, 2])
end
end
return rst
 
end</lang>
function transform(f::BarnsleyFern)
r = rand(0:99)
f.x, f.y = r < 1 ? (0.0, 0.16 * f.y) :
1 <= r < 86 ? (0.85 * f.x + 0.04 * f.y, -0.04 * f.x + 0.85 * f.y + 1.6) :
86 <= r < 93 ? (0.2 * f.x - 0.26 * f.y, 0.23 * f.x + 0.22 * f.y + 1.6) :
(-0.15 * f.x + 0.28 * f.y, 0.26 * f.x + 0.24 * f.y + 0.44)
cx = Int(floor((f.x + 2.182) * (f.width - 1) / 4.8378) + 1)
cy = Int(floor((9.9983 - f.y) * (f.height - 1) / 9.9983) + 1)
f.fern[cx, cy] = f.color
end
 
const fern = BarnsleyFern(500, 500)
for _ in 1:1000000
transform(fern)
end
fern.fern'
</syntaxhighlight>
[[File:Jbarnsleyfern.png]]
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.0
 
import java.awt.*
Line 1,298 ⟶ 2,056:
f.setVisible(true)
}
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def fern
{lambda {:size :sign}
Line 1,321 ⟶ 2,079:
{def F {fern 25 1}}
 
</syntaxhighlight>
</lang>
The output can be seen in http://lambdaway.free.fr/lambdawalks/?view=fern
 
=={{header|Liberty BASIC}}==
 
<langsyntaxhighlight lang="lb">nomainwin
WindowWidth=800
WindowHeight=600
Line 1,356 ⟶ 2,114:
[q]
close #1
</syntaxhighlight>
</lang>
 
=={{header|Locomotive Basic}}==
{{trans|ZX Spectrum Basic}}
[[File:Cpcbasic barnsley.png|thumb|Output with CPCBasic (graphics mode 3)]]
<syntaxhighlight lang="locobasic">10 mode 2:ink 0,0:ink 1,18:randomize time
20 scale=38
30 maxpoints=20000: x=0: y=0
40 for z=1 to maxpoints
50 p=rnd*100
60 if p<=1 then nx=0: ny=0.16*y: goto 100
70 if p<=8 then nx=0.2*x-0.26*y: ny=0.23*x+0.22*y+1.6: goto 100
80 if p<=15 then nx=-0.15*x+0.28*y: ny=0.26*x+0.24*y+0.44: goto 100
90 nx=0.85*x+0.04*y: ny=-0.04*x+0.85*y+1.6
100 x=nx: y=ny
110 plot scale*x+320,scale*y
120 next</syntaxhighlight>
 
=={{header|Lua}}==
Needs L&Ouml;VE 2D Engine
<syntaxhighlight lang="lua">
<lang Lua>
g = love.graphics
wid, hei = g.getWidth(), g.getHeight()
Line 1,394 ⟶ 2,168:
g.draw( canvas )
end
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
BarnsleyFern[{x_, y_}] := Module[{},
i = RandomInteger[{1, 100}];
Line 1,407 ⟶ 2,181:
points = NestList[BarnsleyFern, {0,0}, 100000];
Show[Graphics[{Hue[.35, 1, .7], PointSize[.001], Point[#] & /@ points}]]
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
{{trans|C#}}
{{works with|Mini Micro}}
<syntaxhighlight lang="miniscript">clear
<lang MiniScript>clear
x = 0
y = 0
Line 1,432 ⟶ 2,206:
y = 0.26 * xp + 0.24 * y + 0.44
end if
end for</langsyntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
<lang Nim>
import nimPNG, std/random
 
randomize()
Line 1,484 ⟶ 2,258:
 
for i in 1..iterations:
var r = randomrand(101)
var nx, ny: float
if r <= 85:
Line 1,505 ⟶ 2,279:
 
discard savePNG24("fern.png",img.toString, width, height)
</syntaxhighlight>
</lang>
 
=={{header|Oberon-2}}==
[[File:Barnsleyfern-oberon2.png|250px|thumb|right]]
 
<langsyntaxhighlight lang="oberon2">
MODULE BarnsleyFern;
(**
Line 1,564 ⟶ 2,338:
Init;Draw
END BarnsleyFern.
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Line 1,571 ⟶ 2,345:
[[File:BarnsleyFern.png|right|thumb|Output BarnsleyFern.png]]
 
<langsyntaxhighlight lang="parigp">
\\ Barnsley fern fractal
\\ 6/17/16 aev
Line 1,593 ⟶ 2,367:
pBarnsleyFern(530,100000); \\ BarnsleyFern.png
}
</langsyntaxhighlight>
{{Output}}
Line 1,604 ⟶ 2,378:
=={{header|Perl}}==
[[File:BarnsleyFernPerl.png|250px|thumb|right]]
<langsyntaxhighlight lang="perl">use Imager;
 
my $w = 640;
Line 1,626 ⟶ 2,400:
 
$img->flip(dir => 'v');
$img->write(file => 'barnsleyFern.png');</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
output: [https://imgur.com/a/04ZZZt9 on imgur]
You can run this online [http://phix.x10.mx/p2js/BarnsleyFern.htm here], or see the output [https://imgur.com/a/04ZZZt9 on imgur]
<lang Phix>-- demo\rosetta\BarnsleyFern.exw
<!--<syntaxhighlight lang="phix">(phixonline)-->
include pGUI.e
<span style="color: #000080;font-style:italic;">--
 
-- pwa\phix\BarnsleyFern.exw
Ihandle dlg, canvas
-- =========================
cdCanvas cddbuffer, cdcanvas
--</span>
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
atom {x,y,r} @= 0
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
cdCanvasActivate(cddbuffer)
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
for i=1 to 20000 do
r = rand(100)
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*canvas*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
{x, y} = iff(r<=1? { 0, 0.16*y } :
<span style="color: #004080;">atom</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
iff(r<=8? { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60} :
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
iff(r<=15?{-0.15*x+0.28*y, 0.26*x+0.24*y+0.44} :
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
{ 0.85*x+0.04*y,-0.04*x+0.85*y+1.60})))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100000</span> <span style="color: #008080;">do</span>
cdCanvasPixel(cddbuffer, width/2+x*60, y*60, #00FF00)
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000080;font-style:italic;">-- {x, y} = iff(r&lt;=1? { 0, 0.16*y } :
cdCanvasFlush(cddbuffer)
-- iff(r&lt;=8? { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60} :
return IUP_DEFAULT
-- iff(r&lt;=15?{-0.15*x+0.28*y, 0.26*x+0.24*y+0.44} :
end function
-- { 0.85*x+0.04*y,-0.04*x+0.85*y+1.60})))</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0.16</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span> <span style="color: #0000FF;">}</span>
function map_cb(Ihandle ih)
<span style="color: #008080;">elsif</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">8</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">0.20</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">0.26</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0.23</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.22</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1.60</span><span style="color: #0000FF;">}</span>
cdcanvas = cdCreateCanvas(CD_IUP, ih)
<span style="color: #008080;">elsif</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">15</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">0.15</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.28</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0.26</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.24</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.44</span><span style="color: #0000FF;">}</span>
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
<span style="color: #008080;">else</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">0.85</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.04</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">0.04</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.85</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1.60</span><span style="color: #0000FF;">}</span>
cdCanvasSetBackground(cddbuffer, CD_WHITE)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
cdCanvasSetForeground(cddbuffer, CD_RED)
<span style="color: #7060A8;">cdCanvasPixel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_DARK_GREEN</span><span style="color: #0000FF;">)</span>
return IUP_DEFAULT
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
function esc_close(Ihandle /*ih*/, atom c)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
if c=K_ESC then return IUP_CLOSE end if
return IUP_CONTINUE
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
end function
 
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"RASTERSIZE=340x540"</span><span style="color: #0000FF;">)</span>
procedure main()
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="Barnsley Fern"`</span><span style="color: #0000FF;">)</span>
IupOpen()
 
<span style="color: #7060A8;">IupMap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
canvas = IupCanvas(NULL)
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
IupSetAttribute(canvas, "RASTERSIZE", "340x620") -- initial size
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- release the minimum limitation</span>
 
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
dlg = IupDialog(canvas)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
IupSetAttribute(dlg, "TITLE", "Barnsley Fern")
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<!--</syntaxhighlight>-->
IupMap(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
IupMainLoop()
IupClose()
end procedure
 
main()</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">`(== 64 64)
(seed (in "/dev/urandom" (rd 8)))
(scl 20)
Line 1,721 ⟶ 2,488:
(prinl "P1")
(prinl 640 " " 640)
(mapc prinl G) ) )</langsyntaxhighlight>
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">void setup() {
size(640, 640);
background(0, 0, 0);
Line 1,763 ⟶ 2,530:
}
noLoop();
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">size(640, 640)
background(0)
 
Line 1,827 ⟶ 2,594:
n = height - round(60 * y)
 
set(m, n, "#00ff00")</langsyntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog>
% a straight forward adaption from the Ada example
% these imports are needed for Ciao Prolog but needed
% modules will vary with your Prolog system
:- use_module(library(streams)).
:- use_module(library(stream_utils)).
:- use_module(library(lists)).
:- use_module(library(llists)).
:- use_module(library(hiordlib)).
:- use_module(library(random)).
:- use_module(library(format)).
 
replicate(Term, Times, L) :-
length(L, Times),
maplist(=(Term), L).
 
replace(0, [_|T], E, [E|T]).
replace(X, [H|T0], E, [H|T]) :-
X0 is X -1,
replace(X0, T0, E, T).
replace_2d(X, 0, [H|T], E, [R|T]) :-
replace(X, H, E, R).
replace_2d(X, Y, [H|T0], E, [H|T]) :-
Y0 is Y -1,
replace_2d(X, Y0, T0, E, T).
 
fern_iteration(10000, _X, _Y, Final, Final).
fern_iteration(N, X, Y, I, Final) :-
random(R),
( R =< 0.01
-> ( X1 is 0.0,
Y1 is 0.16*Y )
; ( R =< 0.86
-> ( X1 is 0.85*X + 0.04*Y,
Y1 is -0.04*X + 0.85*Y + 1.6 )
; ( R =< 0.93
-> ( X1 is 0.20*X - 0.26*Y,
Y1 is 0.23*X + 0.22*Y + 1.60 )
; ( X1 is -0.15*X + 0.28*Y,
Y1 is 0.26*X + 0.24*Y + 0.44 )
) ) ),
PointX is 250 + floor(70.0*X1),
PointY is 750 - floor(70.0*Y1),
replace_2d(PointX, PointY, I, [0, 255, 0], I1), !,
N1 is N + 1,
fern_iteration(N1, X1, Y1, I1, Final).
 
draw_fern :-
replicate([0, 0, 0], 500, Row),
replicate(Row, 750, F),
fern_iteration(0, 0, 0, F, Fern),
% the following lines are written for ciao prolog and
% write to a ppm6 file for viewing
% adapting to SWI or Scryer should be straighforward
open('fern.ppm', write, File),
flatten(Fern, FP),
format(File, "P6\n~d ~d\n255\n", [500, 750]),
write_bytes(File, FP),
close(File).
</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DisableDebugger
 
Line 1,871 ⟶ 2,700:
Repeat : Until WaitWindowEvent(50)=#PB_Event_CloseWindow
EndIf
End</langsyntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
 
import random
Line 1,917 ⟶ 2,746:
fern.iterate(1000000)
fern.fern.show()
</syntaxhighlight>
[[File:Pyfern.png]]
 
=={{header|QB64}}==
</lang>
<syntaxhighlight lang="qb64">_Title "Barnsley Fern"
Dim As Integer sw, sh
sw = 400: sh = 600
Screen _NewImage(sw, sh, 8)
 
Dim As Long i, ox, oy
Dim As Single sRand
Dim As Double x, y, x1, y1, sx, sy
sx = 60: sy = 59
ox = 180: oy = 4
Randomize Timer
 
x = 0
y = 0
For i = 1 To 400000
sRand = Rnd
Select Case sRand
Case Is < 0.01
x1 = 0: y1 = 0.16 * y
Case Is < 0.08
x1 = 0.2 * x - 0.26 * y: y1 = 0.23 * x + 0.22 * y + 1.6
Case Is < 0.15
x1 = -0.15 * x + 0.28 * y: y1 = 0.26 * x + 0.24 * y + 0.44
Case Else
x1 = 0.85 * x + 0.04 * y: y1 = -0.04 * x + 0.85 * y + 1.6
End Select
x = x1
y = y1
PSet (x * sx + ox, sh - (y * sy) - oy), 10
Next
 
Sleep
System</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ $ "turtleduck.qky" loadfile ] now!
 
[ ' [ 79 121 66 ] fill
[ 3 2 circle ] ] is dot ( --> )
 
[ 1 fly
-1 4 turn
1 fly
1 4 turn ] is toxy ( n n --> )
 
[ 100 1 v* /
dip [ 100 1 v* / ]
2dup toxy
dot
1 2 turn
toxy
1 2 turn ] is plot ( n n --> )
 
 
[ 2swap 2drop 0 1
2swap 16 100 v* ] is f1 ( n/d n/d --> n/d n/d )
 
[ 2over -4 100 v*
2over 85 100 v*
16 10 v+ v+
join dip
[ 4 100 v*
2swap 85 100 v*
v+ ]
do ] is f2 ( n/d n/d --> n/d n/d )
 
[ 2over 23 100 v*
2over 22 100 v*
16 10 v+ v+
join dip
[ -26 100 v*
2swap 20 100 v*
v+ ]
do ] is f3 ( n/d n/d --> n/d n/d )
 
[ 2over 26 100 v*
2over 24 100 v*
44 100 v+ v+
join dip
[ 28 100 v*
2swap -15 100 v*
v+ ]
do ] is f4 ( n/d n/d --> n/d n/d )
 
[ 100 random
[ dup 0 = iff
[ drop f1 ] done
dup 86 < iff
[ drop f2 ] done
93 < iff f3 done
f4 ]
2swap 1000000000 round
2swap 1000000000 round
2over 2over plot ] is nextpoint ( n/d n/d --> n/d n/d )
 
turtle
' [ 79 121 66 ] colour
-500 1 fly
0 1 0 1
0 frames
20000 times nextpoint
1 frames
4 times drop
</syntaxhighlight>
 
{{out}}
 
[[File:Quackery Barnsley fern.png|thumb|center]]
 
=={{header|R}}==
Line 1,924 ⟶ 2,864:
{{trans|PARI/GP}}
[[File:BarnsleyFernR.png|right|thumb|Output BarnsleyFernR.png]]
<langsyntaxhighlight rlang="rsplus">## pBarnsleyFern(fn, n, clr, ttl, psz=600): Plot Barnsley fern fractal.
## Where: fn - file name; n - number of dots; clr - color; ttl - plot title;
## psz - picture size.
Line 1,958 ⟶ 2,898:
## Executing:
pBarnsleyFern("BarnsleyFernR", 100000, "dark green", "Barnsley Fern Fractal", psz=600)
</langsyntaxhighlight>
 
{{Output}}
Line 1,970 ⟶ 2,910:
==='Obvious' solution===
The matrix solution above is a clever approach, but the following solution is more readable if you're unfamiliar with linear algebra. This is very much a blind "just do what the task says" solution. It's so simple that it probably runs unadapted in S. I suspect that there is room for an interesting use of R's ifelse function somewhere, but I couldn't find a clean way.
<langsyntaxhighlight rlang="rsplus">fernOfNPoints <- function(n)
{
currentX <- currentY <- newX <- newY <- 0
plot(0, 0, xlim = c(-2, 3), ylim = c(0, 10), xlab = "", ylab = "", pch = 20, col = "darkgreen", cex = 0.1)
f1 <- function()#ran 1% of the time
{
newX <<- 0
newY <<- 0.16 * currentY
}
f2 <- function()#ran 85% of the time
{
newX <<- 0.85 * newX + 0.04 * newY
newY <<- -0.1604 *currentY newX + 0.85 * newY + 1.6
}
f2f3 <- function()#ran 857% of the time
{
newX <<- 0.852 * newX+ - 0.0426 * newY
newY <<-- 0.0423 * newX + 0.8522 * newY + 1.6#<<-- is not an error, R's assignment is just that ugly sometimes.
}
f3f4 <- function()#ran 7% of the time
{
newX <<- -0.215 * newX- + 0.2628 * newY
newY <<- 0.2326 * newX + 0.2224 * newY +1 0.644
}
for(i in 2:n)#We've already plotted (0,0), so we can skip one run.
f4<-function()#ran 7% of the time
{
case <- runif(1)
newX<<--0.15*newX+0.28*newY
if(case <= 0.01) f1()
newY<<-0.26*newX+0.24*newY+0.44
else if(case <= 0.86) f2()
else if(case <= 0.93) f3()
else f4()
points(newX, newY, pch = 20, col = "darkgreen", cex = 0.1)
}
for(i in 2:n)#We've already plotted (0,0), so we can skip one run.
{
case<-runif(1)
if(case<=0.01)f1()
else if(case<=0.86)f2()
else if(case<=0.93)f3()
else f4()
points(newX,newY,pch=20,col="darkgreen",cex=0.1)
}
return(invisible())
}
Line 2,009 ⟶ 2,949:
#It will look better if you use a bigger input, but the plot might take a while.
#I find that there's a large delay between RStudio saying that my code is finished running and the plot appearing.
#If your input is truly big, you may want to reduce the two cex parameters (to make the points smaller).</langsyntaxhighlight>
 
=={{header|Racket}}==
[[File:racket-barnsley-fern.png]] : file uploading broken :-(
<langsyntaxhighlight lang="racket">#lang racket
 
(require racket/draw)
Line 2,045 ⟶ 2,985:
 
bmp
(send bmp save-file "images/racket-barnsley-fern.png" 'png)</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,052 ⟶ 2,992:
{{trans|Perl}}
[[File:Barnsley-fern-perl6.png|250px|thumb|right]]
<syntaxhighlight lang="raku" perl6line>use Image::PNG::Portable;
 
my ($w, $h) = (640, 640);
Line 2,068 ⟶ 3,008:
default { ( 0.85 * $x + 0.04 * $y, -0.04 * $x + 0.85 * $y + 1.60) }
};
$png.set(($w / 2 + $x * 60).Int, ($h - ($y * 60).Int, 0, 255, 0);
}
 
$png.write: 'Barnsley-fern-perl6.png';</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,078 ⟶ 3,018:
<br>contains the &nbsp; '''X''' &nbsp; and &nbsp; '''Y''' &nbsp; coördinates for a scatter plot that can be
visualized with a plotting program.
<langsyntaxhighlight lang="rexx">/*REXX pgm gens X & Y coördinates for a scatter plot to be used to show a Barnsley fern.*/
parse arg N FID seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 100000 /*Not specified? Then use the default*/
Line 2,101 ⟶ 3,041:
call lineout FID, x","y
end /*#*/ /* [↓] close the file (safe practice).*/
call lineout FID /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is generated to an output file: &nbsp; BARNSLEY.DAT &nbsp; which contains the &nbsp; '''X''' &nbsp; and &nbsp; '''Y''' &nbsp; coördinates of a scatter plot.}}<br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
<lang Ring>
 
Load "guilib.ring"
Line 2,221 ⟶ 3,161:
return
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
<langsyntaxhighlight lang="ruby">
MAX_ITERATIONS = 200_000
 
Line 2,269 ⟶ 3,209:
size 500, 500
end
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">'Barnsley Fern - Run BASIC
'http://rosettacode.org/wiki/Barnsley_fern#Run_BASIC
'copy code and run it at http://www.runbasic.com
Line 2,302 ⟶ 3,242:
NEXT n
render #g
#g "flush"</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,308 ⟶ 3,248:
{{libheader|rand}}
 
<langsyntaxhighlight lang="rust">extern crate rand;
extern crate raster;
 
Line 2,352 ⟶ 3,292:
 
raster::save(&image, "fractal.png").unwrap();
}</langsyntaxhighlight>
 
=={{header|Scala}}==
===Java Swing Interoperability===
<langsyntaxhighlight Scalalang="scala">import java.awt._
import java.awt.image.BufferedImage
 
Line 2,418 ⟶ 3,358:
})
 
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
This version creates a list of points, defining the fern, which are then rescaled and output to an eps file.
<langsyntaxhighlight lang="scheme">(import (scheme base)
(scheme cxr)
(scheme file)
Line 2,481 ⟶ 3,421:
(display "\n%%EOF")))))
 
(output-fern-as-eps "barnsley.eps" (create-fern 0 0 50000))</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{Works with|Scilab|5.4.0 and above}}
This version creates a list of points, defining the fern, and shows them on a graphic window which can then be saved to a file via the GUI or the console by the user.
<syntaxhighlight lang="text">
iteractions=1.0d6;
 
Line 2,524 ⟶ 3,464:
axes.isoview="on";
axes.children.children.mark_foreground=13;
</syntaxhighlight>
</lang>
 
=={{header|SequenceL}}==
'''Tail-Recursive SequenceL Code:'''<br>
<langsyntaxhighlight lang="sequencel">import <Utilities/Math.sl>;
import <Utilities/Random.sl>;
 
Line 2,559 ⟶ 3,499:
fern := barnsleyFern(seedRandom(seed), count, [[0.0,0.0]]);
in
scale(fern, width, height);</langsyntaxhighlight>
 
'''C++ Driver Code:'''<br>
{{libheader|CImg}}
<langsyntaxhighlight lang="c">#include "SL_Generated.h"
#include "CImg.h"
 
Line 2,596 ⟶ 3,536:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 2,602 ⟶ 3,542:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('Imager')
 
var w = 640
Line 2,624 ⟶ 3,564:
 
img.flip(dir => 'v')
img.write(file => 'barnsleyFern.png')</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/barnsley-fern-sidef.png Barnsley fern]
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">w,h = #.scrsize()
x,y = 0
>
Line 2,641 ⟶ 3,581:
f2(x,y) <= 0.85*x+0.04*y, -0.04*x+0.85*y+1.6
f3(x,y) <= 0.2*x-0.26*y, 0.23*x+0.22*y+1.6
f4(x,y) <= -0.15*x+0.28*y, 0.26*x+0.24*y+0.44</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Works with PolyML. Random generator copy from the [[Random_numbers#Standard_ML]] task. Window slimmed down from [[Animation#Standard_ML]].
<langsyntaxhighlight Standardlang="standard MLml">open XWindows ;
open Motif ;
 
Line 2,704 ⟶ 3,644:
XtRealizeWidget shell
)
end ; </langsyntaxhighlight>
call
demoWindow () ;
 
 
 
=={{header|SuperCollider }}==
{{works with|SuperCollider|3.13.0}}
Submitted to Rosetta Code 2024-06-07 by: MusicCoder.
 
The first line of code excuted is the LAST line in this listing: <br> drawFern.();
 
SuperCollider is a CLIENT / SERVER software system for the generation of music. <br>
CLIENT = (language+IDE) <br>
SERVER = (music-sound engine) <br>
However, the language is a complete / general purpose OO/functional programming language. <br>
SEE: <br>
https://supercollider.github.io/ <br>
https://en.wikipedia.org/wiki/SuperCollider <br>
 
<syntaxhighlight lang="SuperCollider">
// ==========================================================================
// START-SuperCollider solution to Rosetta Code TASK: Barnsley fern
// ==========================================================================
(
/* Barnsley_fern
https://rosettacode.org/wiki/Barnsley_fern
Create this fractal fern, using the following transformations:
ƒ1 1%: xn+1 = 0 yn+1 = 0.16 yn
ƒ2 85%: xn+1 = 0.85 xn + 0.04 yn yn+1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 7% xn+1 = 0.2 xn − 0.26 yn yn+1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 7% xn+1 = −0.15 xn + 0.28 yn yn+1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
 
//BY: MusicCoder : 2024-06-07//
Create arrays to hold the various constants from the formulae above.
Replicate the arrays to create 100 of them,
*** biased by the percentages above ***.
Scramble the 100 arrays of constants.
Function nextXY will pick a set of constants at random and given the current
X and Y values will generate the next X and Y values.
Before we plot the X-Y values run function findScale so that we can make
sure the generated X & Y values will 'fit' within the bounds of the given display size.
 
SuperCollider is a CLIENT / SERVER software system for the generation of music.
CLIENT = (language+IDE)
SERVER = (music-sound engine)
However, the language is a complete / general purpose OO/functional programming language.
https://supercollider.github.io/
https://en.wikipedia.org/wiki/SuperCollider
*/
 
// ==========================================================================
// The first line of code executed is the LAST line in this listing:
// drawFern.();
// ==========================================================================
var fConstants =
// _NEXT_X___________ _NEXT_Y___________
// a*x + b*y +c d*x + e*y + f
( // duplicate each array of constants by the specified % number
([ 0.00, 0.00, 0.00, 0.00, 0.16, 0.00 ]!1 )++ // 1%
([ 0.85, 0.04, 0.00, -0.04, 0.85, 1.6 ]!85)++ // 85%
([ 0.2 , -0.26, 0.00, 0.23, 0.22, 1.6 ]!7 )++ // 7%
([-0.15, 0.28, 0.00, 0.26, 0.24, 0.44 ]!7) // 7%
// the ++ will construct a container array to hold theses arrays
).scramble; // randomly rearrange sub-arrays
// ==========================================================================
var fcSize = fConstants.size;
// ==========================================================================
var nextXY = {|x, y|
var a,b,c,d,e,f;
// split up the array of constants
#a,b,c,d,e,f = fConstants[fcSize.rand];
// apply the constants to the ADD and MUL operations on X and Y
// NEXT_X_________ NEXT_Y___________
[ (a*x) + (b*y) +c, (d*x) + (e*y) + f ]; // return new [x, y]
};
// ==========================================================================
var scaleAndShift = {|num, scale, shift|
roundUp((num*scale)+shift);
};
// ==========================================================================
var findScale = {|screenX=500, screenY=500, runs=1000, show=false|
// use to find min/max in loop of fern functions
var x=0, y=0;
// hold min/max results
var minX=x, maxX=x, minY=y, maxY=y;
// how much 'space' do the X and Y values need
var lengthX, lengthY;
var scaleX, scaleY;
 
// return the following 3 values to position & scale X and Y
// to stay within the given screen size
var shiftX=0; // add to generated X value to position X on screen
var shiftY=0; // add to generated Y value to position Y on screen
var scale; // multiply X and Y to scale the values to stay on the screen
// we need to use the same scaling factor for both X and Y to avoid distortion
 
// find min & max of both X and Y
runs.do {
#x, y = nextXY.(x, y);
if (x<minX) {minX=x};
if (x>maxX) {maxX=x};
if (y<minY) {minY=y};
if (y>maxY) {maxY=y};
};
 
// calculate amount of 'space' needed by X and by Y
lengthX = maxX-minX;
lengthY = maxY-minY;
scaleX = screenX/lengthX;
scaleY = screenY/lengthY;
 
// use the smaller of scaleX and scaleY as we need ONE scale to avoid distortion
// since we have only sampled possible X and Y values ...
// ... reduce scale to 90% of calculated value to allow space to larger X or Y
scale = 0.9*min(scaleX, scaleY);
 
// if min X or Y is negative 'shift' the ZERO point
// so that all neg and pos values are on the screen
if (minX.isNegative) {shiftX = minX.abs * scaleX};
if (minY.isNegative) {shiftY = minY.abs * scaleY};
 
// if calculated shift is 0, to move ZERO away from the edge
// set it as 1% of screen size
// (this is OK as we decreased scale by 10%)
if (shiftX ==0) {shiftX = screenX/100};
if (shiftY ==0) {shiftY = screenY/100};
 
// round up to nearest integer values
# scale, shiftX, shiftY = roundUp([scale, shiftX, shiftY ]);
 
if (show) {
var minXsas = scaleAndShift.(minX, scale, shiftX);
var maxXsas = scaleAndShift.(maxX, scale, shiftX);
var minYsas = scaleAndShift.(minY, scale, shiftY);
var maxYsas = scaleAndShift.(maxY, scale, shiftY);
postln("");
postf("scale=%, shiftX=%, shiftY=%\n", scale, shiftX, shiftY);
postf("MIN scaled & shifted X value=%\n", minXsas);
postf("MIN scaled & shifted Y value=%\n", minYsas);
postf("MAX scaled & shifted X value=% screenX=%\n", maxXsas, screenX);
postf("MAX scaled & shifted Y value=% screenY=%\n", maxYsas, screenY);
};
 
[scale, shiftX, shiftY]; // return these three values
};
// ==========================================================================
var drawFern = {|screenX=400, screenY=600, dotSize=1, windowCorner=50, runs=1000000|
 
var win = Window.new("Barnsley Fern", Rect(windowCorner, windowCorner, screenX, screenY)).front;
var x=0, y=0;
var bigX, bigY;
var scale, shiftX, shiftY;
 
# scale, shiftX, shiftY = findScale.(screenX, screenY, show: true);
win.view.background_(Color.white);
win.drawFunc = {
runs.do {|i|
# x, y = nextXY.(x, y); // generate next X and Y values
bigX = scaleAndShift.(x, scale, shiftX);
// Y=0 is at top of screen,
// so substract Y from screenY to flip orientation
bigY = screenY - scaleAndShift.(y, scale, shiftY);
Pen.color = Color.rand(); // *** JUST FOR FUN: pick a random color ***
Pen.addRect(Rect(bigX, bigY, dotSize, dotSize));
Pen.fill;
}; // end-of: do
}; // end-of: drawFunc
win.refresh;
}; // end-of: drawFern
// ==========================================================================
// The following line of code is executed first:
drawFern.();
)
// ==========================================================================
// **END-SuperCollider solution to Rosetta Code TASK: Barnsley fern
// ==========================================================================
</syntaxhighlight>
 
 
 
 
=={{header|Swift}}==
Output is viewable in a playground.
 
<langsyntaxhighlight lang="swift">import UIKit
import CoreImage
import PlaygroundSupport
Line 2,754 ⟶ 3,873:
}
 
let uiImage = UIImage(cgImage: context.makeImage()!)</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">ClrDraw
Input "ITERS:",M
[[0,0,1]]→[A]
[[0,0,0][0,.16,0][0,0,1]]→[B]
[[.85,-.04,0][.04,.85,0][0,1.6,1]]→[C]
[[.2,.23,0][-.26,.22,0][0,1.6,1]]→[D]
[[-.15,.26,0][.28,.24,0][0,.44,1]]→[E]
0→I
While I<M
randInt(1,100)→R
 
If R=1
Then
[A][B]→[A]
101→R
End
 
If R<86
Then
[A][C]→[A]
101→R
End
 
If R<93
Then
[A][D]→[A]
101→R
End
 
If R<101:Then
[A][E]→[A]
End
 
round([A](1,1)*8+31,0)→E
round([A](1,2)*8,0)→F
Pxl-On(E,F)
I+1→I
End</syntaxhighlight>
 
=={{header|Unicon}}==
{{libheader|graphics}}
<langsyntaxhighlight lang="unicon">
link graphics
 
Line 2,825 ⟶ 3,984:
}
end
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Sub plot_coordinate_pairs(x As Variant, y As Variant)
Dim chrt As Chart
Set chrt = ActiveSheet.Shapes.AddChart.Chart
Line 2,861 ⟶ 4,020:
Next i
plot_coordinate_pairs x, y
End Sub</langsyntaxhighlight>
/* {{header|Visual Basic .NET}} */ Section added
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2011}}
<langsyntaxhighlight lang="vbnet">' Barnsley Fern - 11/11/2019
Public Class BarnsleyFern
 
Line 2,899 ⟶ 4,058:
End Sub 'Paint
 
End Class 'BarnsleyFern</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
 
var Rand = Random.new()
 
class BarnsleyFern {
construct new(width, height, points) {
Window.title = "Barnsley Fern"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_n = points
}
 
init() {
createFern()
}
 
createFern() {
var x = 0
var y = 0
var c = Color.hex("#32cd32")
for (i in 0..._n) {
var tx
var ty
var r = Rand.float()
if (r <= 0.01) {
tx = 0
ty = 0.16 * y
} else if (r <= 0.86) {
tx = 0.85 * x + 0.04 * y
ty = -0.04 * x + 0.85 * y + 1.6
} else if (r <= 0.93) {
tx = 0.2 * x - 0.26 * y
ty = 0.23 * x + 0.22 * y + 1.6
} else {
tx = -0.15 * x + 0.28 * y
ty = 0.26 * x + 0.24 * y + 0.44
}
x = tx
y = ty
Canvas.pset((_w/2 + x * _w/11).round, (_h - y * _h/11).round, c)
}
}
 
update() {}
 
draw(alpha) {}
}
 
var Game = BarnsleyFern.new(640, 640, 200000)</syntaxhighlight>
 
{{out}}
[[File:Wren-Barnsley_fern.png|400px]]
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">int N, R;
real NX, NY, X, Y;
[SetVid($12); \set 640x480x4 VGA graphics (on PC or RPi)
X:= 0.0; Y:= 0.0;
for N:= 0 to 200_000 do
[R:= Ran(100); \0..99
case of
R < 1: [NX:= 0.0; NY:= 0.16*Y];
R < 8: [NX:= 0.20*X - 0.26*Y; NY:= 0.23*X + 0.22*Y + 1.60];
R < 15: [NX:=-0.15*X + 0.28*Y; NY:= 0.26*X + 0.24*Y + 0.44]
other [NX:= 0.85*X + 0.04*Y; NY:=-0.04*X + 0.85*Y + 1.60];
X:= NX; Y:= NY;
Point(320+fix(X*40.0), 440-fix(Y*40.0), 2\green\);
]
]</syntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|ZX Spectrum Basic}}
Classic style
<langsyntaxhighlight Yabasiclang="yabasic">10 REM Fractal Fern
20 LET wid = 800 : LET hei = 600 : open window wid, hei : window origin "cb"
25 backcolor 0, 0, 0 : color 0, 255, 0 : clear window
Line 2,916 ⟶ 4,152:
100 LET x=nx: LET y=ny
110 DOT x*wid/12,y*hei/12
120 NEXT n</langsyntaxhighlight>
Modern style <langsyntaxhighlight Yabasiclang="yabasic">REM Fractal Fern
wid = 800 : hei = 600 : open window wid, hei : window origin "cb"
backcolor 0, 0, 0 : color 0, 255, 0 : clear window
Line 2,930 ⟶ 4,166:
x = nx : y = ny
dot x * wid / 12, y * hei / 12
next</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 2,936 ⟶ 4,172:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
{{trans|Java}}
<langsyntaxhighlight lang="zkl">fcn barnsleyFern(){
w,h:=640,640;
bitmap:=PPM(w+1,h+1,0xFF|FF|FF); // White background
Line 2,951 ⟶ 4,187:
}
bitmap.writeJPGFile("barnsleyFern.jpg");
}();</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
{{trans|zkl}}
<langsyntaxhighlight lang="zxbasic">10 REM Fractal Fern
20 PAPER 7: BORDER 7: BRIGHT 1: INK 4: CLS
30 LET maxpoints=20000: LET x=0: LET y=0
Line 2,967 ⟶ 4,203:
110 PLOT x*17+127,y*17
120 NEXT n
</syntaxhighlight>
</lang>
It is recommended to run on an emulator that supports running at full speed.