mercredi 27 novembre 2019

generic-template function always returning integer values

I am writing the below linear interpolation function, which is meant to be generic, but current result is not.

The function finds desired quantity of equally distant points linear in between two given boundary points. Both desired quantity and boundaries are given as parameters. As return, a vector of linear interpolated values is returned.

The issue I have concerns to return type, which always appear to be integer, even when it should have some mantissa, for example:

lower_limit = 5;
high_limit = 1;
quantity = 3;
return std::vector<int>({4, 3, 2}); // CORRECT

but:

lower_limit = 5;
high_limit = 1;
quantity = 4;
return std::vector<int>({4, 3, 2, 1}); // Not CORRECT
// it should be:
return std::vector<float>({4.2, 3.4, 2.6, 1.8});

What should I do to make it generic and have correct return values?

code:

template <class T>
std::vector<T> interpolatePoints(T lower_limit, T high_limit, const unsigned int quantity) {
    auto distance = abs(std::max(high_limit, lower_limit) - std::min(high_limit, lower_limit));

    auto step = ((1/(double)(quantity+1)) * distance);

    std::vector<T> interpolated_points;
    for(unsigned int i = 1; i <= quantity; i++) {
        if(lower_limit < high_limit) {
            interpolated_points.push_back((std::min(lower_limit, high_limit) + (step*i)));
        } else {
            interpolated_points.push_back((std::max(high_limit, lower_limit) - (step*i)));
        }
    }
    return interpolated_points;
}

Aucun commentaire:

Enregistrer un commentaire