1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.util;
23
24 import org.hipparchus.exception.MathIllegalArgumentException;
25 import org.hipparchus.special.Gamma;
26 import org.junit.jupiter.api.Test;
27
28 import static org.junit.jupiter.api.Assertions.assertEquals;
29 import static org.junit.jupiter.api.Assertions.assertThrows;
30
31
32
33
34 class FactorialLogTest {
35
36 @Test
37 void testPrecondition1() {
38 assertThrows(MathIllegalArgumentException.class, () -> CombinatoricsUtils.FactorialLog.create().withCache(-1));
39 }
40
41 @Test
42 void testNonPositiveArgument() {
43 assertThrows(MathIllegalArgumentException.class, () -> {
44 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
45 f.value(-1);
46 });
47 }
48
49 @Test
50 void testDelegation() {
51 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
52
53
54
55 for (int i = 21; i < 10000; i++) {
56 final double expected = Gamma.logGamma(i + 1);
57 assertEquals(expected, f.value(i), 0d, i + "! ");
58 }
59 }
60
61 @Test
62 void testCompareDirectWithoutCache() {
63
64
65
66 final int max = 100;
67 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
68
69 for (int i = 0; i < max; i++) {
70 final double expected = factorialLog(i);
71 assertEquals(expected, f.value(i), 2 * Math.ulp(expected), i + "! ");
72 }
73 }
74
75 @Test
76 void testCompareDirectWithCache() {
77 final int max = 1000;
78 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create().withCache(max);
79
80 for (int i = 0; i < max; i++) {
81 final double expected = factorialLog(i);
82 assertEquals(expected, f.value(i), 0d, i + "! ");
83 }
84 }
85
86 @Test
87 void testCacheIncrease() {
88 final int max = 100;
89 final CombinatoricsUtils.FactorialLog f1 = CombinatoricsUtils.FactorialLog.create().withCache(max);
90 final CombinatoricsUtils.FactorialLog f2 = f1.withCache(2 * max);
91
92 final int val = max + max / 2;
93 final double expected = factorialLog(val);
94 assertEquals(expected, f2.value(val), 0d);
95 }
96
97 @Test
98 void testCacheDecrease() {
99 final int max = 100;
100 final CombinatoricsUtils.FactorialLog f1 = CombinatoricsUtils.FactorialLog.create().withCache(max);
101 final CombinatoricsUtils.FactorialLog f2 = f1.withCache(max / 2);
102
103 final int val = max / 4;
104 final double expected = factorialLog(val);
105 assertEquals(expected, f2.value(val), 0d);
106 }
107
108
109 private double factorialLog(final int n) {
110 double logSum = 0;
111 for (int i = 2; i <= n; i++) {
112 logSum += FastMath.log(i);
113 }
114 return logSum;
115 }
116 }