Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created April 13, 2012 09:00
Show Gist options
  • Save jmbr/2375233 to your computer and use it in GitHub Desktop.
Save jmbr/2375233 to your computer and use it in GitHub Desktop.
MATLAB's linspace in C++
template <typename T = double>
vector<T> linspace(T a, T b, size_t N) {
T h = (b - a) / static_cast<T>(N-1);
vector<T> xs(N);
typename vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
@garrison
Copy link

garrison commented Aug 8, 2013

Repeated addition of floating point numbers can be numerically unstable. It might instead be better to use a method similar to numpy.linspace, available at https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py

@ozymandium
Copy link

A simple addition would be to set xs.back()=b, if the issue pointed out by @garrison is not a problem.

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