1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.rng.sampling.distribution;
18
19 import org.apache.commons.math3.special.Gamma;
20 import org.apache.commons.rng.sampling.distribution.InternalUtils.FactorialLog;
21 import org.junit.Assert;
22 import org.junit.Test;
23
24
25
26
27 public class InternalUtilsTest {
28
29 private static final int MAX_REPRESENTABLE = 20;
30
31 @Test
32 public void testFactorial() {
33 Assert.assertEquals(1L, InternalUtils.factorial(0));
34 long result = 1;
35 for (int n = 1; n <= MAX_REPRESENTABLE; n++) {
36 result *= n;
37 Assert.assertEquals(result, InternalUtils.factorial(n));
38 }
39 }
40
41 @Test(expected = IndexOutOfBoundsException.class)
42 public void testFactorialThrowsWhenNegative() {
43 InternalUtils.factorial(-1);
44 }
45
46 @Test(expected = IndexOutOfBoundsException.class)
47 public void testFactorialThrowsWhenNotRepresentableAsLong() {
48 InternalUtils.factorial(MAX_REPRESENTABLE + 1);
49 }
50
51 @Test
52 public void testFactorialLog() {
53
54
55 FactorialLog factorialLog = FactorialLog.create().withCache(MAX_REPRESENTABLE / 2);
56 Assert.assertEquals(0, factorialLog.value(0), 1e-10);
57 for (int n = 1; n <= MAX_REPRESENTABLE + 5; n++) {
58
59 double expected = Gamma.logGamma(1 + n);
60 Assert.assertEquals(expected, factorialLog.value(n), 1e-10);
61 }
62 }
63
64 @Test
65 public void testFactorialLogCacheSizeAboveRepresentableFactorials() {
66 final int limit = MAX_REPRESENTABLE + 5;
67 FactorialLog factorialLog = FactorialLog.create().withCache(limit);
68 for (int n = MAX_REPRESENTABLE; n <= limit; n++) {
69
70 double expected = Gamma.logGamma(1 + n);
71 Assert.assertEquals(expected, factorialLog.value(n), 1e-10);
72 }
73 }
74
75 @Test
76 public void testFactorialLogCacheExpansion() {
77
78
79 final FactorialLog factorialLog = FactorialLog.create()
80
81 .withCache(1)
82
83 .withCache(5)
84
85 .withCache(10)
86
87 .withCache(5);
88 for (int n = 1; n <= 5; n++) {
89
90 double expected = Gamma.logGamma(1 + n);
91 Assert.assertEquals(expected, factorialLog.value(n), 1e-10);
92 }
93 }
94
95 @Test(expected = IndexOutOfBoundsException.class)
96 public void testLogFactorialThrowsWhenNegative() {
97 FactorialLog.create().value(-1);
98 }
99
100 @Test(expected = NegativeArraySizeException.class)
101 public void testLogFactorialWithCacheThrowsWhenNegative() {
102 FactorialLog.create().withCache(-1);
103 }
104 }