Skip to content

Instantly share code, notes, and snippets.

@lorenzoriano
Forked from jmbr/linspace.cpp
Last active June 4, 2024 14:29
Show Gist options
  • Save lorenzoriano/5414671 to your computer and use it in GitHub Desktop.
Save lorenzoriano/5414671 to your computer and use it in GitHub Desktop.
C++ Analogous of Python linspace, returns a std::vector
template <typename T>
std::vector<T> linspace(T a, T b, size_t N) {
T h = (b - a) / static_cast<T>(N-1);
std::vector<T> xs(N);
typename std::vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
@lagordon70
Copy link

I was looking for some help porting over some python and found your project -- here's something that worked for me, more accurately, for doing numpy linspace -- it's important to do all the math in floating point -- hope this helps

/* a function to generate numpy linspace */
template <typename T>
std::vector<T> linspace(double start, double end, double num)
{
    std::vector<T> linspaced;

    if (0 != num)
    {
        if (1 == num) 
        {
            linspaced.push_back(static_cast<T>(start));
        }
        else
        {
            double delta = (end - start) / (num - 1);

            for (auto i = 0; i < (num - 1); ++i)
            {
                linspaced.push_back(static_cast<T>(start + delta * i));
            }
            // ensure that start and end are exactly the same as the input
            linspaced.push_back(static_cast<T>(end));
        }
    }
    return linspaced;
}

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