1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.linear;
18
19 import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
20 import org.apache.commons.numbers.combinatorics.BinomialCoefficient;
21
22
23
24
25
26 public class InverseHilbertMatrix
27 extends RealLinearOperator {
28
29
30 private final int n;
31
32
33
34
35
36
37 public InverseHilbertMatrix(final int n) {
38 this.n = n;
39 }
40
41
42 @Override
43 public int getColumnDimension() {
44 return n;
45 }
46
47
48
49
50
51
52
53
54
55 public long getEntry(final int i, final int j) {
56 long val = i + j + 1;
57 long aux = BinomialCoefficient.value(n + i, n - j - 1);
58 val = Math.multiplyExact(val, aux);
59 aux = BinomialCoefficient.value(n + j, n - i - 1);
60 val = Math.multiplyExact(val, aux);
61 aux = BinomialCoefficient.value(i + j, i);
62 val = Math.multiplyExact(val, aux);
63 val = Math.multiplyExact(val, aux);
64 return ((i + j) & 1) == 0 ? val : -val;
65 }
66
67
68 @Override
69 public int getRowDimension() {
70 return n;
71 }
72
73
74 @Override
75 public RealVector operate(final RealVector x) {
76 if (x.getDimension() != n) {
77 throw new DimensionMismatchException(x.getDimension(), n);
78 }
79 final double[] y = new double[n];
80 for (int i = 0; i < n; i++) {
81 double pos = 0.;
82 double neg = 0.;
83 for (int j = 0; j < n; j++) {
84 final double xj = x.getEntry(j);
85 final long coeff = getEntry(i, j);
86 final double daux = coeff * xj;
87
88
89
90 if (daux > 0.) {
91 pos += daux;
92 } else {
93 neg += daux;
94 }
95 }
96 y[i] = pos + neg;
97 }
98 return new ArrayRealVector(y, false);
99 }
100 }