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
27 import org.junit.Assert;
28 import org.junit.Test;
29
30
31
32
33 public class FactorialLogTest {
34
35 @Test(expected=MathIllegalArgumentException.class)
36 public void testPrecondition1() {
37 CombinatoricsUtils.FactorialLog.create().withCache(-1);
38 }
39
40 @Test(expected=MathIllegalArgumentException.class)
41 public void testNonPositiveArgument() {
42 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
43 f.value(-1);
44 }
45
46 @Test
47 public void testDelegation() {
48 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
49
50
51
52 for (int i = 21; i < 10000; i++) {
53 final double expected = Gamma.logGamma(i + 1);
54 Assert.assertEquals(i + "! ",
55 expected, f.value(i), 0d);
56 }
57 }
58
59 @Test
60 public void testCompareDirectWithoutCache() {
61
62
63
64 final int max = 100;
65 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create();
66
67 for (int i = 0; i < max; i++) {
68 final double expected = factorialLog(i);
69 Assert.assertEquals(i + "! ",
70 expected, f.value(i), 2 * Math.ulp(expected));
71 }
72 }
73
74 @Test
75 public void testCompareDirectWithCache() {
76 final int max = 1000;
77 final CombinatoricsUtils.FactorialLog f = CombinatoricsUtils.FactorialLog.create().withCache(max);
78
79 for (int i = 0; i < max; i++) {
80 final double expected = factorialLog(i);
81 Assert.assertEquals(i + "! ",
82 expected, f.value(i), 0d);
83 }
84 }
85
86 @Test
87 public 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 Assert.assertEquals(expected, f2.value(val), 0d);
95 }
96
97 @Test
98 public 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 Assert.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 }