1 /*
2 * Licensed to the Hipparchus project 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 * https://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.hipparchus.optim.nonlinear.vector.leastsquares;
18
19 import org.hipparchus.optim.ConvergenceChecker;
20 import org.hipparchus.optim.nonlinear.vector.leastsquares.LeastSquaresProblem.Evaluation;
21 import org.hipparchus.util.Precision;
22
23 /**
24 * Check if an optimization has converged based on the change in computed RMS.
25 *
26 */
27 public class EvaluationRmsChecker implements ConvergenceChecker<Evaluation> {
28
29 /** relative tolerance for comparisons. */
30 private final double relTol;
31 /** absolute tolerance for comparisons. */
32 private final double absTol;
33
34 /**
35 * Create a convergence checker for the RMS with the same relative and absolute
36 * tolerance.
37 *
38 * <p>Convenience constructor for when the relative and absolute tolerances are the
39 * same. Same as {@code new EvaluationRmsChecker(tol, tol)}.
40 *
41 * @param tol the relative and absolute tolerance.
42 * @see #EvaluationRmsChecker(double, double)
43 */
44 public EvaluationRmsChecker(final double tol) {
45 this(tol, tol);
46 }
47
48 /**
49 * Create a convergence checker for the RMS with a relative and absolute tolerance.
50 *
51 * <p>The optimization has converged when the RMS of consecutive evaluations are equal
52 * to within the given relative tolerance or absolute tolerance.
53 *
54 * @param relTol the relative tolerance.
55 * @param absTol the absolute tolerance.
56 * @see Precision#equals(double, double, double)
57 * @see Precision#equalsWithRelativeTolerance(double, double, double)
58 */
59 public EvaluationRmsChecker(final double relTol, final double absTol) {
60 this.relTol = relTol;
61 this.absTol = absTol;
62 }
63
64 /** {@inheritDoc} */
65 @Override
66 public boolean converged(final int iteration,
67 final Evaluation previous,
68 final Evaluation current) {
69 final double prevRms = previous.getRMS();
70 final double currRms = current.getRMS();
71 return Precision.equals(prevRms, currRms, this.absTol) ||
72 Precision.equalsWithRelativeTolerance(prevRms, currRms, this.relTol);
73 }
74
75 }