5
\$\begingroup\$

I wrote a compile time bernstein polynomial instead to define several functions for different coefficients. I wonder whether there is a way to make the function faster. std::powf is known to be relatively slow and the binominal coefficient is for some cases 1. Also style fixes are appreciated.

// Template functions to estimate the binominal coefficient
template<uint8_t n, uint8_t k>
struct binomial {
  static constexpr int value = (binomial<n - 1, k - 1>::value + binomial<n - 1, k>::value);
};

template<>
struct binomial<0, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, n> {
  static constexpr int value = 1;
};

// Template bernstein polynomial
template <uint8_t n, uint8_t k>
float bernstein(const float val) {
  constexpr float binom_coeff = binomial<n, k>::value;
  const float a = std::powf(val, k);
  const float b = std::powf(1 - val, n - k);
  return binom_coeff * a * b;
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You could check against the most common cases you expect to occur:

float a;
switch (k)
{
case 0:
    a = 1.0f;
    break;
case 1:
    a = val;
    break;
case 2:
    a = val*val;
    break;
// maybe some more common cases...
default:
    a = std::powf(val, k);
}

But I personally wouldn't do such optimizations unless you really see that there is some significant slowdown in your particular case and benchmarks show that such an optimization really does make a difference.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.