Skip to content

Mathematical Rose Patterns ​

A table of roses, r = cos(n/d · θ), with n along the columns and d along the rows. After the Coding Train's Mathematical Rose Patterns.

js
const count = Inputs.range([2, 20], {label: "Count", step: 1, value: 10});
js
const size = 640;
const vector = d3.range(count);
const scale = d3.scaleBand(vector, [0, size]).padding(0.1);
const r = scale.bandwidth() / 2;

function gcd(a, b) {
  return b ? gcd(b, a % b) : a;
}

function rose(n, d) {
  const k = n / d;
  const turns = d / gcd(n, d);
  const points = [];
  for (let a = 0; a < Math.PI * 2 * turns + 0.02; a += 0.02) {
    const r1 = r * Math.cos(k * a);
    points.push([r1 * Math.cos(a), r1 * Math.sin(a)]);
  }
  return d3.line()(points);
}

const svg = cm.svg`<svg ${{width: size, height: size, viewBox: [0, 0, size, size], stroke_width: 1.2}}>
  <g ${{data: d3.cross(vector, vector), transform: ([x, y]) => `translate(${scale(x) + r}, ${scale(y) + r})`}}>
    <path ${{d: ([x, y]) => rose(x + 1, y + 1), stroke: "black", fill: "none"}}/>
  </g>
</svg>`;

document.body.append(svg);