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, () -> {
39 CombinatoricsUtils.FactorialLog.create().withCache(-1);
40 });
41 }
42
43 @Test
44 void testNonPositiveArgument() {
45 assertThrows(MathIllegalArgumentException.class, () -> {
46 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
47 f.value(-1);
48 });
49 }
50
51 @Test
52 void testDelegation() {
53 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
54
55
56
57 for (int i = 21; i < 10000; i++) {
58 final double expected = Gamma.logGamma(i + 1);
59 assertEquals(expected, f.value(i), 0d, i + "! ");
60 }
61 }
62
63 @Test
64 void testCompareDirectWithoutCache() {
65
66
67
68 final int max = 100;
69 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
70
71 for (int i = 0; i < max; i++) {
72 final double expected = factorialLog(i);
73 assertEquals(expected, f.value(i), 2 * Math.ulp(expected), i + "! ");
74 }
75 }
76
77 @Test
78 void testCompareDirectWithCache() {
79 final int max = 1000;
80 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create().withCache(max);
81
82 for (int i = 0; i < max; i++) {
83 final double expected = factorialLog(i);
84 assertEquals(expected, f.value(i), 0d, i + "! ");
85 }
86 }
87
88 @Test
89 void testCacheIncrease() {
90 final int max = 100;
91 final CombinatoricsUtils.FactorialLog f1 = CombinatoricsUtils.FactorialLog.create().withCache(max);
92 final CombinatoricsUtils.FactorialLog f2 = f1.withCache(2 * max);
93
94 final int val = max + max / 2;
95 final double expected = factorialLog(val);
96 assertEquals(expected, f2.value(val), 0d);
97 }
98
99 @Test
100 void testCacheDecrease() {
101 final int max = 100;
102 final CombinatoricsUtils.FactorialLog f1 = CombinatoricsUtils.FactorialLog.create().withCache(max);
103 final CombinatoricsUtils.FactorialLog f2 = f1.withCache(max / 2);
104
105 final int val = max / 4;
106 final double expected = factorialLog(val);
107 assertEquals(expected, f2.value(val), 0d);
108 }
109
110
111 private double factorialLog(final int n) {
112 double logSum = 0;
113 for (int i = 2; i <= n; i++) {
114 logSum += FastMath.log(i);
115 }
116 return logSum;
117 }
118 }