Skip to content

Instantly share code, notes, and snippets.

@Pyknic
Created September 11, 2019 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pyknic/b885f434c5b08ba91434079cdf549240 to your computer and use it in GitHub Desktop.
Save Pyknic/b885f434c5b08ba91434079cdf549240 to your computer and use it in GitHub Desktop.
C++ Discretization
//
// Copyright (c) 2019 Emil Forslund. All rights reserved.
//
#include "discrete.hpp"
Discrete::Discrete(float min, float, max, uint16_t buckets) :
min{min},
discreteFactor{buckets / (max - min)},
continuousFactor{(max - min) / buckets},
buckets{buckets} {}
uint16_t Discrete::toDiscrete(float value) const {
return discreteFactor * (value - min);
}
float Discrete::fromDiscrete(uint16_t value) const {
return continuousFactor * value + min;
}
float Discrete::fromDiscrete(uint16_t value, float interpolation) const {
return continuousFactor * (value + interpolation) + min;
}
void Discrete::forEach(const std::function<void(float)> &action) const {
for (uint16_t i = 0; i < buckets; i++) {
const float value {fromDiscrete(i)};
action(value);
}
}
//
// Copyright (c) 2019 Emil Forslund. All rights reserved.
//
#ifndef SPATIAL_TRACKING_DISCRETE_HPP
#define SPATIAL_TRACKING_DISCRETE_HPP
#include <cstdint>
#include <functional>
class Discrete {
public:
Discrete(float min, float max, uint16_t buckets);
uint16_t toDiscrete(float value) const;
float fromDiscrete(uint16_t value) const;
float fromDiscrete(uint16_t value, float interpolation) const;
void forEach(const std::function<void(float)>& action) const;
private:
float min, discreteFactor, continuousFactor;
uint16_t buckets;
};
#endif //SPATIAL_TRACKING_DISCRETE_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment