distribution.cxx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // distribution.cpp
  3. // shared_random_generator
  4. //
  5. // Created by Sam Jaffe on 3/25/23.
  6. // Copyright © 2023 Sam Jaffe. All rights reserved.
  7. //
  8. #include "random/distribution.h"
  9. #include <iostream>
  10. #include <random>
  11. #include <sstream>
  12. #include "random/device.h"
  13. #define INSTANTIATE_DISTRIBUTION_TEMPLATES(T) \
  14. template std::string to_string(Distribution<T> const &); \
  15. template class Uniform<T>;
  16. namespace engine::random {
  17. template <typename T> std::string to_string(Distribution<T> const & dist) {
  18. std::stringstream ss;
  19. ss << dist;
  20. return ss.str();
  21. }
  22. template <typename Rand>
  23. Uniform<Rand>::Uniform(Rand min)
  24. : Uniform(min, std::numeric_limits<Rand>::max()) {}
  25. template <typename Rand>
  26. Uniform<Rand>::Uniform(Rand min, Rand max) : min_(min), max_(max) {}
  27. template <typename Rand>
  28. auto Uniform<Rand>::operator()(Device & device) const -> result_type {
  29. if constexpr (std::is_floating_point_v<Rand>) {
  30. return std::uniform_real_distribution<Rand>(min_, max_)(device);
  31. } else {
  32. return std::uniform_int_distribution<Rand>(min_, max_)(device);
  33. }
  34. }
  35. template <typename Rand> void Uniform<Rand>::describe(std::ostream & os) const {
  36. constexpr char close = std::is_floating_point_v<Rand> ? ')' : ']';
  37. os << typeid(Rand).name() << "Uniform[" << min_ << ',' << max_ << close;
  38. }
  39. IMPLEMENT_DEVICE(INSTANTIATE_DISTRIBUTION_TEMPLATES)
  40. }