Home | History | Annotate | Download | only in test
      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 (at) 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 
     10 #include "main.h"
     11 
     12 #include <Eigen/CXX11/Tensor>
     13 
     14 static void test_default()
     15 {
     16   Tensor<float, 1> vec(6);
     17   vec.setRandom();
     18 
     19   // Fixme: we should check that the generated numbers follow a uniform
     20   // distribution instead.
     21   for (int i = 1; i < 6; ++i) {
     22     VERIFY_IS_NOT_EQUAL(vec(i), vec(i-1));
     23   }
     24 }
     25 
     26 static void test_normal()
     27 {
     28   Tensor<float, 1> vec(6);
     29   vec.setRandom<Eigen::internal::NormalRandomGenerator<float>>();
     30 
     31   // Fixme: we should check that the generated numbers follow a gaussian
     32   // distribution instead.
     33   for (int i = 1; i < 6; ++i) {
     34     VERIFY_IS_NOT_EQUAL(vec(i), vec(i-1));
     35   }
     36 }
     37 
     38 
     39 struct MyGenerator {
     40   MyGenerator() { }
     41   MyGenerator(const MyGenerator&) { }
     42 
     43   // Return a random value to be used.  "element_location" is the
     44   // location of the entry to set in the tensor, it can typically
     45   // be ignored.
     46   int operator()(Eigen::DenseIndex element_location, Eigen::DenseIndex /*unused*/ = 0) const {
     47     return static_cast<int>(3 * element_location);
     48   }
     49 
     50   // Same as above but generates several numbers at a time.
     51   internal::packet_traits<int>::type packetOp(
     52       Eigen::DenseIndex packet_location, Eigen::DenseIndex /*unused*/ = 0) const {
     53     const int packetSize = internal::packet_traits<int>::size;
     54     EIGEN_ALIGN_MAX int values[packetSize];
     55     for (int i = 0; i < packetSize; ++i) {
     56       values[i] = static_cast<int>(3 * (packet_location + i));
     57     }
     58     return internal::pload<typename internal::packet_traits<int>::type>(values);
     59   }
     60 };
     61 
     62 
     63 static void test_custom()
     64 {
     65   Tensor<int, 1> vec(6);
     66   vec.setRandom<MyGenerator>();
     67 
     68   for (int i = 0; i < 6; ++i) {
     69     VERIFY_IS_EQUAL(vec(i), 3*i);
     70   }
     71 }
     72 
     73 void test_cxx11_tensor_random()
     74 {
     75   CALL_SUBTEST(test_default());
     76   CALL_SUBTEST(test_normal());
     77   CALL_SUBTEST(test_custom());
     78 }
     79