View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math4.legacy.linear;
18  
19  import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
20  
21  /** This class implements Hilbert Matrices as {@link RealLinearOperator}. */
22  public class HilbertMatrix
23      extends RealLinearOperator {
24  
25      /** The size of the matrix. */
26      private final int n;
27  
28      /**
29       * Creates a new instance of this class.
30       *
31       * @param n Size of the matrix to be created..
32       */
33      public HilbertMatrix(final int n) {
34          this.n = n;
35      }
36  
37      /** {@inheritDoc} */
38      @Override
39      public int getColumnDimension() {
40          return n;
41      }
42  
43      /** {@inheritDoc} */
44      @Override
45      public int getRowDimension() {
46          return n;
47      }
48  
49      /** {@inheritDoc} */
50      @Override
51      public RealVector operate(final RealVector x) {
52          if (x.getDimension() != n) {
53              throw new DimensionMismatchException(x.getDimension(), n);
54          }
55          final double[] y = new double[n];
56          for (int i = 0; i < n; i++) {
57              double pos = 0.;
58              double neg = 0.;
59              for (int j = 0; j < n; j++) {
60                  final double xj = x.getEntry(j);
61                  final double coeff = 1. / (i + j + 1.);
62                  // Positive and negative values are sorted out in order to limit
63                  // catastrophic cancellations (do not forget that Hilbert
64                  // matrices are *very* ill-conditioned!
65                  if (xj > 0.) {
66                      pos += coeff * xj;
67                  } else {
68                      neg += coeff * xj;
69                  }
70              }
71              y[i] = pos + neg;
72          }
73          return new ArrayRealVector(y, false);
74      }
75  }