Skip to content

Instantly share code, notes, and snippets.

@joates
Created September 16, 2013 18:56
Show Gist options
  • Save joates/6584908 to your computer and use it in GitHub Desktop.
Save joates/6584908 to your computer and use it in GitHub Desktop.
linspace(a, b, n) from Numeric Javascript by Sébastien Loisel (https://github.com/sloisel/numeric/blob/master/src/numeric.js#L922)
numeric.linspace = function linspace(a,b,n) {
if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1);
if(n<2) { return n===1?[a]:[]; }
var i,ret = Array(n);
n--;
for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; }
return ret;
}
@Tasades
Copy link

Tasades commented Jan 5, 2021

some tests

describe('Linspace tests', () => {
  it('should return correct array with linspace', () => {
    expect(linspace(12, 12, 0)).toEqual([])
    expect(linspace(12, 12, 1)).toEqual([12])
    expect(linspace(12, 13, 1)).toEqual([12])
    expect(linspace(12, 13, 2)).toEqual([12, 13])
    expect(linspace(12, 24, 5)).toEqual([12, 15, 18, 21, 24])
    expect(linspace(12, 24, 4)).toEqual([12, 16, 20, 24])

    expect(linspace(12, 11, 0)).toEqual([])
    expect(linspace(12, 11, 1)).toEqual([12])
    expect(linspace(12, 11, 2)).toEqual([12, 11])

    expect(linspace(12, 1, 0)).toEqual([])
    expect(linspace(12, 1, 1)).toEqual([12])
    expect(linspace(12, 1, 2)).toEqual([12, 1])
    expect(linspace(12, 1, 5)).toEqual([12, 9.25, 6.5, 3.75, 1])
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment