Program Listing for File math_utils.h

Return to documentation for file (src/bitrl/utils/maths/math_utils.h)

#include "bitrl/bitrl_types.h"


#include <algorithm>
#include <cmath>
#include <vector>
#include <cassert>

namespace bitrl{
namespace utils{
namespace maths{

template<typename T>
int_t
sign(const T& expr){

    if(expr < 0){
        return -1;
    }

    return 1;
}

template<typename T>
int_t
sign(const T& expr1, const T& expr2){
    return sign(expr1*expr2);
}

template<typename T>
T sum_sqr(const DynVec<T>& vec){

    T sum_ = T(0);
    for(uint_t i = 0; i<vec.size(); ++i){
        sum_ += vec[i] * vec[i];
    }

    return sum_;
}

template<typename T>
T
sqr(const T& v){
    return v*v;
}

template <typename VectorType>
uint_t
arg_max(const VectorType& vec) {
  return static_cast<uint_t>(std::distance(vec.begin(), std::max_element(vec.begin(), vec.end())));
}


template <typename VectorType>
uint_t
arg_min(const VectorType& vec) {
  return static_cast<uint_t>(std::distance(vec.begin(), std::min_element(vec.begin(), vec.end())));
}

template <typename VectorType>
typename VectorType::value_type
max(const VectorType& vec) {
  return *std::max_element(vec.begin(), vec.end());
}

template <typename VectorType>
typename VectorType::value_type
min(const VectorType& vec) {
  return *std::min_element(vec.begin(), vec.end());
}

namespace{

    template<typename T>
    auto lin_value(T start, T stop, uint_t index, uint_t n){

        assert(n > 1 && index < n);
        const auto amount = static_cast<T>(index) / (n -1);
        const auto v = std::lerp(start, stop, amount);
        return v;
    }

}

template<typename T>
std::vector<T>
lin_space(T start, T stop, uint_t n){

    auto v = std::vector<T>{};
    v.reserve(n);
    for(auto i=0u; i<n; ++i){
        v.push_back(lin_value(start, stop, i, n));
    }
    return v;
}


}
}
}