Home > database >  Inner product of compile-time coefficients and sequence of values
Inner product of compile-time coefficients and sequence of values

Time:01-24

Looking to calculate the inner product of a series of floating point values and corresponding coefficients (given that the coefficients are known at compile-time).

template <uint64_t Divisor, uint64_t... Coefficients>
static consteval std::array<double, sizeof...(Coefficients)> createCoefficients()
{
    double coeff[] = {Coefficients...};
    for (auto& c : coeff)
        c /= Divisor;
    return std::to_array(coeff);
}

template <uint64_t Divisor, uint64_t... Coefficients>
static constexpr auto inner_product(std::floating_point auto... values) requires(sizeof...(values) == sizeof...(Coefficients))
{
    constexpr auto coeff = createCoefficients<Divisor, Coefficients...>();
    std::initializer_list<double> il({values...});
    return std::inner_product(coeff.begin(), coeff.end(), il.begin(), 0);
}

I would like to simplify this as I have a feeling the interface is not as clean as I would like. Are there any improvements that could be made here?

CodePudding user response:

This appears way too complicated. Something along these lines perhaps:

template <uint64_t Divisor, uint64_t... Coefficients>
static constexpr auto inner_product(std::floating_point auto... values)
{
    return ((values * Coefficients / Divisor)   ...);
}

Demo

  •  Tags:  
  • Related