Created
April 13, 2012 09:00
-
-
Save jmbr/2375233 to your computer and use it in GitHub Desktop.
MATLAB's linspace in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
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