cxx11_tensor_random.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. #include "main.h"
  10. #include <Eigen/CXX11/Tensor>
  11. template<typename Scalar>
  12. static void test_default()
  13. {
  14. Tensor<Scalar, 1> vec(6);
  15. vec.setRandom();
  16. // Fixme: we should check that the generated numbers follow a uniform
  17. // distribution instead.
  18. for (int i = 1; i < 6; ++i) {
  19. VERIFY_IS_NOT_EQUAL(vec(i), vec(i-1));
  20. }
  21. }
  22. template<typename Scalar>
  23. static void test_normal()
  24. {
  25. Tensor<Scalar, 1> vec(6);
  26. vec.template setRandom<Eigen::internal::NormalRandomGenerator<Scalar>>();
  27. // Fixme: we should check that the generated numbers follow a gaussian
  28. // distribution instead.
  29. for (int i = 1; i < 6; ++i) {
  30. VERIFY_IS_NOT_EQUAL(vec(i), vec(i-1));
  31. }
  32. }
  33. struct MyGenerator {
  34. MyGenerator() { }
  35. MyGenerator(const MyGenerator&) { }
  36. // Return a random value to be used. "element_location" is the
  37. // location of the entry to set in the tensor, it can typically
  38. // be ignored.
  39. int operator()(Eigen::DenseIndex element_location, Eigen::DenseIndex /*unused*/ = 0) const {
  40. return static_cast<int>(3 * element_location);
  41. }
  42. // Same as above but generates several numbers at a time.
  43. internal::packet_traits<int>::type packetOp(
  44. Eigen::DenseIndex packet_location, Eigen::DenseIndex /*unused*/ = 0) const {
  45. const int packetSize = internal::packet_traits<int>::size;
  46. EIGEN_ALIGN_MAX int values[packetSize];
  47. for (int i = 0; i < packetSize; ++i) {
  48. values[i] = static_cast<int>(3 * (packet_location + i));
  49. }
  50. return internal::pload<typename internal::packet_traits<int>::type>(values);
  51. }
  52. };
  53. static void test_custom()
  54. {
  55. Tensor<int, 1> vec(6);
  56. vec.setRandom<MyGenerator>();
  57. for (int i = 0; i < 6; ++i) {
  58. VERIFY_IS_EQUAL(vec(i), 3*i);
  59. }
  60. }
  61. EIGEN_DECLARE_TEST(cxx11_tensor_random)
  62. {
  63. CALL_SUBTEST((test_default<float>()));
  64. CALL_SUBTEST((test_normal<float>()));
  65. CALL_SUBTEST((test_default<double>()));
  66. CALL_SUBTEST((test_normal<double>()));
  67. CALL_SUBTEST((test_default<Eigen::half>()));
  68. CALL_SUBTEST((test_normal<Eigen::half>()));
  69. CALL_SUBTEST((test_default<Eigen::bfloat16>()));
  70. CALL_SUBTEST((test_normal<Eigen::bfloat16>()));
  71. CALL_SUBTEST(test_custom());
  72. }