Skip to content

Instantly share code, notes, and snippets.

@MehdiNS
Created April 26, 2017 13:13
Show Gist options
  • Save MehdiNS/7286250c54236dfdab58fc8256ae08ad to your computer and use it in GitHub Desktop.
Save MehdiNS/7286250c54236dfdab58fc8256ae08ad to your computer and use it in GitHub Desktop.
Compile time generation of Halton sequences
// Works with C++14 compiler
// Had to use my own array instead of std::array but with a C++17 compiler, it "should work" (tm) without it.
// Also, could use some static_assert here and there....
#include <iostream>
#include <cmath>
using namespace std;
constexpr float halton(int i, int base)
{
float x = 1.f / base;
float v = 0.f;
while (i > 0)
{
v += x * (i % base);
i = floor(i / base);
x /= base;
}
return v;
}
struct Point2
{
float x, y;
constexpr Point2(float xx = 0.f, float yy = 0.f) : x{xx}, y{yy} {}
};
template <class T, std::size_t N>
class ConstexprArray {
public:
using size_type = std::size_t;
using value_type = T;
private:
value_type vals[N];
public:
constexpr const value_type& operator[](size_type n) const {
return vals[n];
}
constexpr value_type& operator[](size_type n) {
return vals[n];
}
};
template <std::size_t N, int base1, int base2>
constexpr auto generateHaltonSequence() {
ConstexprArray<Point2, N> res;
for (std::size_t i = 1; i < N+1; ++i)
res[i-1] = Point2(halton(i, base1), halton(i, base2));
return res;
}
int main()
{
constexpr const auto haltonLUT = generateHaltonSequence<256,2,3>();
/*
Do stuff
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment