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; | |
} |
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
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
I think it would be better to leave out the default argument, I get the following error:
make -k
g++ vector_plot.cpp gnuplot.cpp -o vector -lboost_iostreams -lboost_system -lboost_filesystem
gnuplot.cpp:21:43: error: default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x
make: *** [all] Error 1
Compilation exited abnormally with code 2 at Sat Jun 29 15:11:35