Sunflower fractal: Difference between revisions
Clarify task |
m →{{header|Phix}}: added syntax colouring and run online link |
||
Line 472: | Line 472: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/pGUI}} |
{{libheader|Phix/pGUI}} |
||
{{libheader|Phix/online}} |
|||
<lang Phix>constant numberofseeds = 3000 |
|||
You can run this online [http://phix.x10.mx/p2js/SunflowerFractal.htm here]. |
|||
<!--<lang Phix>(phixonline)--> |
|||
include pGUI.e |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<span style="color: #008080;">constant</span> <span style="color: #000000;">numberofseeds</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3000</span> |
|||
Ihandle dlg, canvas |
|||
cdCanvas cddbuffer, cdcanvas |
|||
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> |
|||
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) |
|||
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span> |
|||
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span> |
|||
integer {hw, hh} = sq_floor_div(IupGetIntInt(canvas, "DRAWSIZE"),2) |
|||
atom s = min(hw,hh)/150, |
|||
<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;">/*ih*/</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> |
|||
f = min(hw,hh)*8/125 |
|||
cdCanvasActivate(cddbuffer) |
|||
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hh</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_floor_div</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><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
|||
cdCanvasClear(cddbuffer) |
|||
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hh</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">150</span><span style="color: #0000FF;">,</span> |
|||
atom c = (sqrt(5)+1)/2 |
|||
<span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hh</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">8</span><span style="color: #0000FF;">/</span><span style="color: #000000;">125</span> |
|||
for i=0 to numberofseeds do |
|||
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span> |
|||
atom r = power(i,c)/numberofseeds, |
|||
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span> |
|||
angle = 2*PI*c*i, |
|||
<span style="color: #004080;">atom</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span> |
|||
x = s*r*sin(angle)+hw, |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">numberofseeds</span> <span style="color: #008080;">do</span> |
|||
y = s*r*cos(angle)+hh |
|||
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">numberofseeds</span><span style="color: #0000FF;">,</span> |
|||
cdCanvasCircle(cddbuffer,x,y,i/numberofseeds*f) |
|||
<span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> |
|||
end for |
|||
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">,</span> |
|||
cdCanvasFlush(cddbuffer) |
|||
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">hh</span> |
|||
return IUP_DEFAULT |
|||
<span style="color: #7060A8;">cdCanvasCircle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</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: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">numberofseeds</span><span style="color: #0000FF;">*</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> |
|||
end function |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span> |
|||
function map_cb(Ihandle ih) |
|||
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> |
|||
cdcanvas = cdCreateCanvas(CD_IUP, ih) |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) |
|||
cdCanvasSetBackground(cddbuffer, CD_WHITE) |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span> |
|||
cdCanvasSetForeground(cddbuffer, CD_BLACK) |
|||
<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;">ih</span><span style="color: #0000FF;">)</span> |
|||
return IUP_DEFAULT |
|||
<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> |
|||
end function |
|||
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLACK</span><span style="color: #0000FF;">)</span> |
|||
procedure main() |
|||
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> |
|||
IupOpen() |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
canvas = IupCanvas(NULL) |
|||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
|||
IupSetAttribute(canvas, "RASTERSIZE", "602x502") -- initial size |
|||
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span> |
|||
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) |
|||
<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: #004600;">NULL</span><span style="color: #0000FF;">)</span> |
|||
dlg = IupDialog(canvas) |
|||
<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: #008000;">"602x502"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- initial size</span> |
|||
IupSetAttribute(dlg, "TITLE", "Sunflower") |
|||
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">))</span> |
|||
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) |
|||
<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> |
|||
IupMap(dlg) |
|||
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Sunflower"</span><span style="color: #0000FF;">)</span> |
|||
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation |
|||
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ACTION"</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> |
|||
IupShowXY(dlg,IUP_CENTER,IUP_CENTER) |
|||
IupMainLoop() |
|||
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span> |
|||
IupClose() |
|||
<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> |
|||
end procedure |
|||
<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> |
|||
main()</lang> |
|||
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span> |
|||
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
|||
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
|||
<!--</lang>--> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
Revision as of 11:12, 18 September 2021
Draw a Sunflower fractal
11l
<lang 11l>-V
phi = (1 + sqrt(5)) / 2 size = 600 seeds = 5 * size
print(‘<svg xmlns="http://www.w3.org/2000/svg" width="’size‘" height="’size‘" style="stroke:gold">’) print(‘<rect width="100%" height="100%" fill="black" />’)
L(i) 1..seeds
V r = 2 * (i ^ phi) / seeds V t = 2 * math:pi * phi * i print(‘<circle cx="#.2" cy="#.2" r="#.1" />’.format(r * sin(t) + size / 2, r * cos(t) + size / 2, sqrt(i) / 13))
print(‘</svg>’)</lang>
C
The colouring of the "fractal" is determined with every iteration to ensure that the resulting graphic looks similar to a real Sunflower, thus the parameter diskRatio determines the radius of the central disk as the maximum radius of the flower is known from the number of iterations. The scaling factor is currently hardcoded but can also be externalized. Requires the WinBGIm library.
<lang C> /*Abhishek Ghosh, 14th September 2018*/
- include<graphics.h>
- include<math.h>
- define pi M_PI
void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter;
int i;
setbkcolor(LIGHTBLUE);
for(i=0;i<=iter;i++){ r = pow(i,factor)/iter;
r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);
theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } }
int main() { initwindow(1000,1000,"Sunflower...");
sunflower(1000,1000,0.5,3000);
getch();
closegraph();
return 0; } </lang>
C++
<lang cpp>#include <cmath>
- include <fstream>
- include <iostream>
bool sunflower(const char* filename) {
std::ofstream out(filename); if (!out) return false;
constexpr int size = 600; constexpr int seeds = 5 * size; constexpr double pi = 3.14159265359; constexpr double phi = 1.61803398875; out << "<svg xmlns='http://www.w3.org/2000/svg\' width='" << size; out << "' height='" << size << "' style='stroke:gold'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << std::setprecision(2) << std::fixed; for (int i = 1; i <= seeds; ++i) { double r = 2 * std::pow(i, phi)/seeds; double theta = 2 * pi * phi * i; double x = r * std::sin(theta) + size/2; double y = r * std::cos(theta) + size/2; double radius = std::sqrt(i)/13; out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n"; } out << "</svg>\n"; return true;
}
int main(int argc, char *argv[]) {
if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } if (!sunflower(argv[1])) { std::cerr << "image generation failed\n"; return EXIT_FAILURE; } return EXIT_SUCCESS;
}</lang>
- Output:
See: sunflower.svg (offsite SVG image)
FreeBASIC
<lang freebasic> Const PI As Double = 4 * Atn(1) Const ancho = 400 Const alto = 400
Screenres ancho, alto, 8 Windowtitle" Pulsa una tecla para finalizar" Cls
Sub Sunflower(semillas As Integer)
Dim As Double c = (Sqr(5)+1)/2 For i As Integer = 0 To semillas Dim As Double r = (i^c) / semillas Dim As Double angulo = 2 * Pi * c * i Dim As Double x = r * Sin(angulo) + 200 Dim As Double y = r * Cos(angulo) + 200 Circle (x, y), i/semillas*10, i/semillas*10 Next i
End Sub
Sunflower(2000) Bsave "sunflower_fractal.bmp",0 Sleep End </lang>
Go
The image produced, when viewed with (for example) EOG, is similar to the Ring entry.
<lang go>package main
import (
"github.com/fogleman/gg" "math"
)
func main() {
dc := gg.NewContext(400, 400) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 1) c := (math.Sqrt(5) + 1) / 2 numberOfSeeds := 3000 for i := 0; i <= numberOfSeeds; i++ { fi := float64(i) fn := float64(numberOfSeeds) r := math.Pow(fi, c) / fn angle := 2 * math.Pi * c * fi x := r*math.Sin(angle) + 200 y := r*math.Cos(angle) + 200 fi /= fn / 5 dc.DrawCircle(x, y, fi) } dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("sunflower_fractal.png")
}</lang>
JavaScript
HTML to test
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Sunflower</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body{background-color:black;text-align:center;margin-top:150px} </style> <script src="sunflower.js"></script> </head> <body onload="start()"> <div id='wnd'></div> </body> </html>
<lang javascript>const SIZE = 400, HS = SIZE >> 1, WAIT = .005, SEEDS = 3000,
TPI = Math.PI * 2, C = (Math.sqrt(10) + 1) / 2;
class Sunflower {
constructor() { this.wait = WAIT; this.colorIndex = 0; this.dimension = 0; this.lastTime = 0; this.accumulator = 0; this.deltaTime = 1 / 60; this.colors = ["#ff0000", "#ff8000", "#ffff00", "#80ff00", "#00ff00", "#00ff80", "#00ffff", "#0080ff", "#0000ff", "#8000ff", "#ff00ff", "#ff0080"]; this.canvas = document.createElement('canvas'); this.canvas.width = SIZE; this.canvas.height = SIZE; const d = document.getElementById("wnd"); d.appendChild(this.canvas); this.ctx = this.canvas.getContext('2d'); } draw(clr, d) { let r = Math.pow(d, C) / SEEDS; let angle = TPI * C * d; let x = HS + r * Math.sin(angle), y = HS + r * Math.cos(angle); this.ctx.strokeStyle = clr; this.ctx.beginPath(); this.ctx.arc(x, y, d / (SEEDS / 50), 0, TPI); this.ctx.closePath(); this.ctx.stroke(); } update(dt) { if((this.wait -= dt) < 0) { this.draw(this.colors[this.colorIndex], this.dimension); this.wait = WAIT; if((this.dimension++) > 600) { this.dimension = 0; this.colorIndex = (this.colorIndex + 1) % this.colors.length; } } } start() { this.loop = (time) => { this.accumulator += (time - this.lastTime) / 1000; while(this.accumulator > this.deltaTime) { this.accumulator -= this.deltaTime; this.update(Math.min(this.deltaTime)); } this.lastTime = time; requestAnimationFrame(this.loop); } this.loop(0); }
} function start() {
const sunflower = new Sunflower(); sunflower.start();
}</lang>
Julia
Run from REPL. <lang julia>using Makie
function sunflowerplot()
len = 2000 ϕ = 0.5 + sqrt(5) / 2 r = LinRange(0.0, 100.0, len) θ = zeros(len) markersizes = zeros(Int, len) for i in 2:length(r) θ[i] = θ[i - 1] + 2π * ϕ markersizes[i] = div(i, 500) + 3 end x = r .* cos.(θ) y = r .* sin.(θ) scene = Scene(backgroundcolor=:green) scatter!(scene, x, y, color=:gold, markersize=markersizes, strokewidth=1, fill=false, show_axis=false)
end
sunflowerplot() </lang>
Liberty BASIC
<lang lb> nomainwin UpperLeftX=1:UpperLeftY=1 WindowWidth=800:WindowHeight=600 open "Sunflower Fractal" for graphics_nf_nsb as #1
- 1 "trapclose [q];down;fill darkred;flush;size 3"
c=1.618033988749895 seeds=8000 rd=gn=bl=int(rnd(1)*255)
for i=0 to seeds rd=rd+5:if rd>254 then rd=1 gn=gn+3:if gn>254 then gn=1 bl=bl+1:if bl>254 then bl=1 #1 "color ";rd;" ";gn;" ";bl #1 "backcolor ";rd;" ";gn;" ";bl r=(i^c)/seeds angle=2*3.14159*c*i x=r*sin(angle)+400 y=r*cos(angle)+280 #1 "place ";x;" ";y #1 "circlefilled ";i/seeds*5 scan next i wait
[q]
close #1 end
</lang>
Mathematica / Wolfram Language
<lang Mathematica>numseeds = 3000; pts = Table[
i = N[ni]; r = i^GoldenRatio/numseeds; t = 2 Pi GoldenRatio i; Circle[AngleVector[{r, t}], i/(numseeds/3)] , {ni, numseeds} ];
Graphics[pts]</lang>
Microsoft Small Basic
<lang smallbasic>' Sunflower fractal - 24/07/2018
GraphicsWindow.Width=410 GraphicsWindow.Height=400 c=(Math.SquareRoot(5)+1)/2 numberofseeds=3000 For i=0 To numberofseeds r=Math.Power(i,c)/numberofseeds angle=2*Math.Pi*c*i x=r*Math.Sin(angle)+200 y=r*Math.Cos(angle)+200 GraphicsWindow.DrawEllipse(x, y, i/numberofseeds*10, i/numberofseeds*10) EndFor </lang>
- Output:
Nim
<lang Nim>import math import imageman
const
Size = 600 Background = ColorRGBU [byte 0, 0, 0] Foreground = ColorRGBU [byte 0, 255, 0] C = (sqrt(5.0) + 1) / 2 NumberOfSeeds = 6000 Fn = float(NumberOfSeeds)
var image = initImage[ColorRGBU](Size, Size) image.fill(Background)
for i in 0..<NumberOfSeeds:
let fi = float(i) r = pow(fi, C) / Fn angle = 2 * PI * C * fi x = toInt(r * sin(angle) + Size div 2) y = toInt(r * cos(angle) + Size div 2) image.drawCircle(x, y, toInt(8 * fi / Fn), Foreground)
image.savePNG("sunflower.png", compression = 9)</lang>
Objeck
<lang perl>use Game.SDL2; use Game.Framework;
class Test {
@framework : GameFramework; @colors : Color[]; function : Main(args : String[]) ~ Nil { Test->New()->Run(); } New() { @framework := GameFramework->New(GameConsts->SCREEN_WIDTH, GameConsts->SCREEN_HEIGHT, "Test"); @framework->SetClearColor(Color->New(0, 0, 0)); @colors := Color->New[2]; @colors[0] := Color->New(255,128,0); @colors[1] := Color->New(255,255,25); } method : Run() ~ Nil { if(@framework->IsOk()) { e := @framework->GetEvent(); quit := false; while(<>quit) { # process input while(e->Poll() <> 0) { if(e->GetType() = EventType->SDL_QUIT) { quit := true; }; };
@framework->FrameStart(); Render(525,525,0.50,3000); @framework->FrameEnd(); }; } else { "--- Error Initializing Environment ---"->ErrorLine(); return; };
leaving { @framework->Quit(); }; }
method : Render(winWidth : Int, winHeight : Int, diskRatio : Float, iter : Int) ~ Nil { renderer := @framework->GetRenderer();
@framework->Clear();
factor := 0.5 + 1.25->SquareRoot(); x := winWidth / 2.0; y := winHeight / 2.0; maxRad := Float->Power(iter, factor) / iter;
for(i:=0;i<=iter;i+=1;) { r := Float->Power(i,factor)/iter; color := r/maxRad < diskRatio ? @colors[0] : @colors[1]; theta := 2*Float->Pi()*factor*i; renderer->CircleColor(x + r*theta->Sin(), y + r*theta->Cos(), 10 * i/(1.0*iter), color); }; @framework->Show(); }
}
consts GameConsts {
SCREEN_WIDTH := 640, SCREEN_HEIGHT := 480
} </lang>
Perl
<lang perl>use utf8; use constant π => 3.14159265; use constant φ => (1 + sqrt(5)) / 2;
my $scale = 600; my $seeds = 5*$scale;
print qq{<svg xmlns="http://www.w3.org/2000/svg" width="$scale" height="$scale" style="stroke:gold">
<rect width="100%" height="100%" fill="black" />\n};
for $i (1..$seeds) {
$r = 2 * ($i**φ) / $seeds; $t = 2 * π * φ * $i; $x = $r * sin($t) + $scale/2; $y = $r * cos($t) + $scale/2; printf qq{<circle cx="%.2f" cy="%.2f" r="%.1f" />\n}, $x, $y, sqrt($i)/13;
}
print "</svg>\n";</lang> See Phi-packing image (SVG image)
Phix
You can run this online here.
with javascript_semantics constant numberofseeds = 3000 include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) integer {hw, hh} = sq_floor_div(IupGetIntInt(canvas, "DRAWSIZE"),2) atom s = min(hw,hh)/150, f = min(hw,hh)*8/125 cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) atom c = (sqrt(5)+1)/2 for i=0 to numberofseeds do atom r = power(i,c)/numberofseeds, angle = 2*PI*c*i, x = s*r*sin(angle)+hw, y = s*r*cos(angle)+hh cdCanvasCircle(cddbuffer,x,y,i/numberofseeds*f) end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "602x502") -- initial size IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) dlg = IupDialog(canvas) IupSetAttribute(dlg, "TITLE", "Sunflower") IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
Python
<lang python> from turtle import * from math import *
- Based on C implementation
iter = 3000 diskRatio = .5
factor = .5 + sqrt(1.25)
screen = getscreen()
(winWidth, winHeight) = screen.screensize()
- x = winWidth/2.0
- y = winHeight/2.0
x = 0.0 y = 0.0
maxRad = pow(iter,factor)/iter;
bgcolor("light blue")
hideturtle()
tracer(0, 0)
for i in range(iter+1):
r = pow(i,factor)/iter; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter))
update()
done() </lang>
R
<lang R> phi=1/2+sqrt(5)/2 r=seq(0,1,length.out=2000) theta=numeric(length(r)) theta[1]=0 for(i in 2:length(r)){
theta[i]=theta[i-1]+phi*2*pi
} x=r*cos(theta) y=r*sin(theta) par(bg="black") plot(x,y) size=seq(.5,2,length.out = length(x)) thick=seq(.1,2,length.out = length(x)) for(i in 1:length(x)){
points(x[i],y[i],cex=size[i],lwd=thick[i],col="goldenrod1")
} </lang>
- Output:
Racket
<lang racket>#lang racket
(require 2htdp/image)
(define N 3000) (define DISK-RATIO 0.5) (define factor (+ 0.5 (sqrt 1.25))) (define WIDTH 500) (define HEIGHT 500) (define max-rad (/ (expt N factor) N))
(for/fold ([image (empty-scene WIDTH HEIGHT)]) ([i (in-range N)])
(define r (/ (expt i factor) N)) (define color (if (< (/ r max-rad) DISK-RATIO) 'brown 'darkyellow)) (define theta (* 2 pi factor i)) (place-image (circle (* 10 i (/ 1 N)) 'outline color) (+ (/ WIDTH 2) (* r (sin theta))) (+ (/ HEIGHT 2) (* r (cos theta))) image))</lang>
Raku
(formerly Perl 6)
This is not really a fractal. It is more accurately an example of a Fibonacci spiral or Phi-packing.
Or, to be completely accurate: It is a variation of a generative Fermat's spiral using the Vogel model to implement phi-packing. See: https://thatsmaths.com/2014/06/05/sunflowers-and-fibonacci-models-of-efficiency
<lang perl6>use SVG;
my $seeds = 3000; my @center = 300, 300; my $scale = 5;
constant \φ = (3 - 5.sqrt) / 2;
my @c = map {
my ($x, $y) = ($scale * .sqrt) «*« |cis($_ * φ * τ).reals »+« @center; [ $x.round(.01), $y.round(.01), (.sqrt * $scale / 100).round(.1) ]
}, 1 .. $seeds;
say SVG.serialize(
svg => [ :600width, :600height, :style<stroke:yellow>, :rect[:width<100%>, :height<100%>, :fill<black>], |@c.map( { :circle[:cx(.[0]), :cy(.[1]), :r(.[2])] } ), ],
);</lang> See: Phi packing (SVG image)
Ring
<lang ring>
- Project : Sunflower fractal
load "guilib.ring"
paint = null
new qapp
{ win1 = new qwidget() { setwindowtitle("Sunflower fractal") setgeometry(100,100,320,500) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext("") } new qpushbutton(win1) { setgeometry(100,400,100,30) settext("draw") setclickevent("draw()") } show() } exec() }
func draw
p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) setpen(pen)
c = (sqrt(5) + 1) / 2 numberofseeds = 3000 for i = 0 to numberofseeds r = pow(i, c ) / (numberofseeds) angle = 2 * 3.14 * c * i x = r * sin(angle) + 100 y = r * cos(angle) + 100 drawellipse(x, y, i / (numberofseeds / 10), i / (numberofseeds / 10)) next
endpaint() } label1 { setpicture(p1) show() }
</lang> Output:
Sidef
<lang ruby>require('Imager')
func draw_sunflower(seeds=3000) {
var img = %O<Imager>.new( xsize => 400, ysize => 400, )
var c = (sqrt(1.25) + 0.5) { |i| var r = (i**c / seeds) var θ = (2 * Num.pi * c * i) var x = (r * sin(θ) + 200) var y = (r * cos(θ) + 200) img.circle(x => x, y => y, r => i/(5*seeds)) } * seeds
return img
}
var img = draw_sunflower() img.write(file => "sunflower.png")</lang> Output image: Sunflower fractal
Wren
<lang ecmascript>import "graphics" for Canvas, Color import "dome" for Window
class Game {
static init() { Window.title = "Sunflower fractal" var width = 400 var height = 400 Window.resize(width, height) Canvas.resize(width, height) Canvas.cls(Color.black) var col = Color.green var seeds = 3000 sunflower(seeds, col) }
static update() {}
static draw(alpha) {}
static sunflower(seeds, col) { var c = (5.sqrt + 1) / 2 for (i in 0..seeds) { var r = i.pow(c) / seeds var angle = 2 * Num.pi * c * i var x = r*angle.sin + 200 var y = r*angle.cos + 200 Canvas.circle(x, y, i/seeds*5, col) } }
}</lang>
zkl
Uses Image Magick and the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl <lang zkl>fcn sunflower(seeds=3000){
img,color := PPM(400,400), 0x00ff00; // green c:=((5.0).sqrt() + 1)/2; foreach n in ([0.0 .. seeds]){ // floats r:=n.pow(c)/seeds; x,y := r.toRectangular(r.pi*c*n*2); r=(n/seeds*5).toInt(); img.circle(200 + x, 200 + y, r,color); } img.writeJPGFile("sunflower.zkl.jpg");
}();</lang>
- Output:
Image at sunflower fractal