EJW
EJW

Reputation: 614

Making a simple Javascript version of a gaussian distribution

I am trying to draw a series of rectangles (or lines) that follow the height of a gaussian curve. I will need to tweak the distribution manually, because I want to accomplish the very specific curve attached - where it goes up to a spike and back down - reference image here Or is there an easier equation to just start small, get large, then small again?

Based on the gaussian curve function I have tried this:

var a = 10;
var b = 10;
var x = 20;
var c = 10;

for (var j=0; j< 15; j++){
r.rect(100+j*12, 10, 6, 10*j*((a * Math.E) - (Math.pow(j-b),2))/(Math.pow(c,2)))
.fill(0)
}

if the r.rect looks weird, it's from the rune.js library.

Upvotes: 1

Views: 2723

Answers (1)

noahnu
noahnu

Reputation: 3574

Your math is incorrect. Here is what you wrote in standard mathematical notation:

enter image description here

I'm not familiar with rune.js, however, here's a simple implementation of a Gaussian curve in pure JS.

const a = 100
const b = 25
const c = 10

const cv = document.getElementById('c')
const ctx = cv.getContext('2d')

for (let j = 0; j < 150; j++) {
    const y = a / (Math.E ** (((j - b) ** 2) / (2 * (c ** 2))))
    ctx.rect(j * 10, cv.height - y, 10, y)
    ctx.stroke()
}
<canvas id="c" height="200" width="500" />

Upvotes: 2

Related Questions