aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/pythran/pythran/pythonic/numpy/random/binomial.hpp
blob: b0b556bc113d52a580fd2f6545e2a19faeabef12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef PYTHONIC_NUMPY_RANDOM_BINOMIAL_HPP
#define PYTHONIC_NUMPY_RANDOM_BINOMIAL_HPP

#include "pythonic/include/numpy/random/binomial.hpp"

#include "pythonic/types/ndarray.hpp"
#include "pythonic/types/numpy_expr.hpp"

#include "pythonic/types/exceptions.hpp"

PYTHONIC_NS_BEGIN
namespace numpy
{
  namespace random
  {
    namespace details
    {
      inline void parameters_check(double n, double p)
      {
        if (n < 0)
          throw pythonic::types::ValueError("n < 0");
        if (p < 0)
          throw pythonic::types::ValueError("p < 0");
        else if (p > 1)
          throw pythonic::types::ValueError("p > 1");
      }
    } // namespace details

    template <class pS>
    types::ndarray<long, pS> binomial(double n, double p, pS const &shape)
    {
      details::parameters_check(n, p);
      types::ndarray<long, pS> result{shape, types::none_type()};
      std::binomial_distribution<long> distribution{(long)n, p};
      std::generate(result.fbegin(), result.fend(),
                    [&]() { return distribution(details::generator); });
      return result;
    }

    inline auto binomial(double n, double p, long size)
        -> decltype(binomial(n, p, types::array_tuple<long, 1>{{size}}))
    {
      return binomial(n, p, types::array_tuple<long, 1>{{size}});
    }

    inline long binomial(double n, double p, types::none_type d)
    {
      details::parameters_check(n, p);
      return std::binomial_distribution<long>{(long)n, p}(details::generator);
    }
  } // namespace random
} // namespace numpy
PYTHONIC_NS_END

#endif