This commit is contained in:
Gilles Sadowski 2021-06-25 14:51:00 +02:00
commit c98e638d73
92 changed files with 5454 additions and 5019 deletions

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -45,13 +45,13 @@ class ChineseRings {
* @param numPointsRing1 Number of points in the first ring. * @param numPointsRing1 Number of points in the first ring.
* @param numPointsRing2 Number of points in the second ring. * @param numPointsRing2 Number of points in the second ring.
*/ */
public ChineseRings(Vector3D orientationRing1, ChineseRings(Vector3D orientationRing1,
double radiusRing1, double radiusRing1,
double halfWidthRing1, double halfWidthRing1,
double radiusRing2, double radiusRing2,
double halfWidthRing2, double halfWidthRing2,
int numPointsRing1, int numPointsRing1,
int numPointsRing2) { int numPointsRing2) {
// First ring (centered at the origin). // First ring (centered at the origin).
final Vector3D[] firstRing = new Vector3D[numPointsRing1]; final Vector3D[] firstRing = new Vector3D[numPointsRing1];
// Second ring (centered around the first ring). // Second ring (centered around the first ring).
@ -113,6 +113,8 @@ class ChineseRings {
/** /**
* Gets all the points. * Gets all the points.
*
* @return the points
*/ */
public Vector3D[] getPoints() { public Vector3D[] getPoints() {
return points.clone(); return points.clone();
@ -125,24 +127,28 @@ class ChineseRings {
*/ */
public Iterable<double[]> createIterable() { public Iterable<double[]> createIterable() {
return new Iterable<double[]>() { return new Iterable<double[]>() {
@Override
public Iterator<double[]> iterator() { public Iterator<double[]> iterator() {
return new Iterator<double[]>() { return new Iterator<double[]>() {
/** Data. */ /** Data. */
final Vector3D[] points = getPoints(); private final Vector3D[] points = getPoints();
/** Number of samples. */ /** Number of samples. */
private int n = 0; private int n = 0;
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public boolean hasNext() { public boolean hasNext() {
return n < points.length; return n < points.length;
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public double[] next() { public double[] next() {
return points[n++].toArray(); return points[n++].toArray();
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public void remove() { public void remove() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -26,7 +26,6 @@ import org.apache.commons.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math4.neuralnet.SquareNeighbourhood; import org.apache.commons.math4.neuralnet.SquareNeighbourhood;
import org.apache.commons.math4.neuralnet.FeatureInitializer; import org.apache.commons.math4.neuralnet.FeatureInitializer;
import org.apache.commons.math4.neuralnet.FeatureInitializerFactory; import org.apache.commons.math4.neuralnet.FeatureInitializerFactory;
import org.apache.commons.math4.neuralnet.MapUtils;
import org.apache.commons.math4.neuralnet.DistanceMeasure; import org.apache.commons.math4.neuralnet.DistanceMeasure;
import org.apache.commons.math4.neuralnet.EuclideanDistance; import org.apache.commons.math4.neuralnet.EuclideanDistance;
import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D; import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
@ -54,9 +53,9 @@ class ChineseRingsClassifier {
* @param dim1 Number of rows of the SOFM. * @param dim1 Number of rows of the SOFM.
* @param dim2 Number of columns of the SOFM. * @param dim2 Number of columns of the SOFM.
*/ */
public ChineseRingsClassifier(ChineseRings rings, ChineseRingsClassifier(ChineseRings rings,
int dim1, int dim1,
int dim2) { int dim2) {
this.rings = rings; this.rings = rings;
sofm = new NeuronSquareMesh2D(dim1, false, sofm = new NeuronSquareMesh2D(dim1, false,
dim2, false, dim2, false,
@ -164,24 +163,27 @@ class ChineseRingsClassifier {
private Iterator<double[]> createRandomIterator(final long numSamples) { private Iterator<double[]> createRandomIterator(final long numSamples) {
return new Iterator<double[]>() { return new Iterator<double[]>() {
/** Data. */ /** Data. */
final Vector3D[] points = rings.getPoints(); private final Vector3D[] points = rings.getPoints();
/** RNG. */ /** RNG. */
final UniformRandomProvider rng = RandomSource.create(RandomSource.KISS); private final UniformRandomProvider rng = RandomSource.create(RandomSource.KISS);
/** Number of samples. */ /** Number of samples. */
private long n = 0; private long n = 0;
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public boolean hasNext() { public boolean hasNext() {
return n < numSamples; return n < numSamples;
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public double[] next() { public double[] next() {
++n; ++n;
return points[rng.nextInt(points.length)].toArray(); return points[rng.nextInt(points.length)].toArray();
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override
public void remove() { public void remove() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -35,19 +35,23 @@ import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
*/ */
@Command(description = "Run the application", @Command(description = "Run the application",
mixinStandardHelpOptions = true) mixinStandardHelpOptions = true)
public class StandAlone implements Callable<Void> { public final class StandAlone implements Callable<Void> {
/** The number of rows. */
@Option(names = { "-r" }, paramLabel = "numRows", @Option(names = { "-r" }, paramLabel = "numRows",
description = "Number of rows of the 2D SOFM (default: ${DEFAULT-VALUE}).") description = "Number of rows of the 2D SOFM (default: ${DEFAULT-VALUE}).")
private int _numRows = 15; private int numRows = 15;
/** The number of columns. */
@Option(names = { "-c" }, paramLabel = "numCols", @Option(names = { "-c" }, paramLabel = "numCols",
description = "Number of columns of the 2D SOFM (default: ${DEFAULT-VALUE}).") description = "Number of columns of the 2D SOFM (default: ${DEFAULT-VALUE}).")
private int _numCols = 15; private int numCols = 15;
/** The number of samples. */
@Option(names = { "-s" }, paramLabel = "numSamples", @Option(names = { "-s" }, paramLabel = "numSamples",
description = "Number of samples for the training (default: ${DEFAULT-VALUE}).") description = "Number of samples for the training (default: ${DEFAULT-VALUE}).")
private long _numSamples = 100000; private long numSamples = 100000;
/** The output file. */
@Option(names = { "-o" }, paramLabel = "outputFile", required = true, @Option(names = { "-o" }, paramLabel = "outputFile", required = true,
description = "Output file name.") description = "Output file name.")
private String _outputFile = null; private String outputFile = null;
/** /**
* Program entry point. * Program entry point.
@ -65,9 +69,9 @@ public class StandAlone implements Callable<Void> {
20, 1, 20, 1,
2000, 1500); 2000, 1500);
final ChineseRingsClassifier classifier = new ChineseRingsClassifier(rings, _numRows, _numCols); final ChineseRingsClassifier classifier = new ChineseRingsClassifier(rings, numRows, numCols);
classifier.createSequentialTask(_numSamples).run(); classifier.createSequentialTask(numSamples).run();
printResult(_outputFile, classifier); printResult(outputFile, classifier);
return null; return null;
} }
@ -81,10 +85,11 @@ public class StandAlone implements Callable<Void> {
* @throws FileNotFoundException If the file cannot be created. * @throws FileNotFoundException If the file cannot be created.
*/ */
private static void printResult(String fileName, private static void printResult(String fileName,
ChineseRingsClassifier sofm) throws FileNotFoundException, UnsupportedEncodingException { ChineseRingsClassifier sofm)
throws FileNotFoundException, UnsupportedEncodingException {
final NeuronSquareMesh2D.DataVisualization result = sofm.computeQualityIndicators(); final NeuronSquareMesh2D.DataVisualization result = sofm.computeQualityIndicators();
try (final PrintWriter out = new PrintWriter(fileName, StandardCharsets.UTF_8.name())) { try (PrintWriter out = new PrintWriter(fileName, StandardCharsets.UTF_8.name())) {
out.println("# Number of samples: " + result.getNumberOfSamples()); out.println("# Number of samples: " + result.getNumberOfSamples());
out.println("# Quantization error: " + result.getMeanQuantizationError()); out.println("# Quantization error: " + result.getMeanQuantizationError());
out.println("# Topographic error: " + result.getMeanTopographicError()); out.println("# Topographic error: " + result.getMeanTopographicError());

View File

@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Self-organized feature map (SOFM) used for classification.
*/
package org.apache.commons.math4.examples.sofm.chineserings;

View File

@ -16,11 +16,13 @@
*/ */
package org.apache.commons.math3.examples.neuralnet.sofm.tsp; package org.apache.commons.math3.examples.neuralnet.sofm.tsp;
import org.apache.commons.rng.simple.RandomSource;
/** /**
* Application class.
*/ */
public class StandAlone { public final class StandAlone {
/** No instances. */
private StandAlone() {}
/** /**
* Program entry point. * Program entry point.
* *

View File

@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Self-organized feature map (ANN) sample codes.
*/
package org.apache.commons.math3.examples.neuralnet.sofm.tsp;

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -26,11 +26,11 @@ import java.util.HashSet;
*/ */
public class City { public class City {
/** Identifier. */ /** Identifier. */
final String name; private final String name;
/** x-coordinate. */ /** x-coordinate. */
final double x; private final double x;
/** y-coordinate. */ /** y-coordinate. */
final double y; private final double y;
/** /**
* @param name Name. * @param name Name.
@ -56,7 +56,7 @@ public class City {
* @return the (x, y) coordinates. * @return the (x, y) coordinates.
*/ */
public double[] getCoordinates() { public double[] getCoordinates() {
return new double[] { x, y }; return new double[] {x, y};
} }
/** /**
@ -116,7 +116,7 @@ public class City {
++count; ++count;
} }
return new double[] { xB / count, yB / count }; return new double[] {xB / count, yB / count};
} }
/** /**

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -35,22 +35,27 @@ import org.apache.commons.rng.simple.RandomSource;
*/ */
@Command(description = "Run the application", @Command(description = "Run the application",
mixinStandardHelpOptions = true) mixinStandardHelpOptions = true)
public class StandAlone implements Callable<Void> { public final class StandAlone implements Callable<Void> {
/** The neurons per city. */
@Option(names = { "-n" }, paramLabel = "neuronsPerCity", @Option(names = { "-n" }, paramLabel = "neuronsPerCity",
description = "Average number of neurons per city (default: ${DEFAULT-VALUE}).") description = "Average number of neurons per city (default: ${DEFAULT-VALUE}).")
private double _neuronsPerCity = 2.2; private double neuronsPerCity = 2.2;
/** The number of samples. */
@Option(names = { "-s" }, paramLabel = "numSamples", @Option(names = { "-s" }, paramLabel = "numSamples",
description = "Number of samples for the training (default: ${DEFAULT-VALUE}).") description = "Number of samples for the training (default: ${DEFAULT-VALUE}).")
private long _numSamples = 2000L; private long numSamples = 2000L;
/** The number of jobs. */
@Option(names = { "-j" }, paramLabel = "numJobs", @Option(names = { "-j" }, paramLabel = "numJobs",
description = "Number of concurrent tasks (default: ${DEFAULT-VALUE}).") description = "Number of concurrent tasks (default: ${DEFAULT-VALUE}).")
private int _numJobs = Runtime.getRuntime().availableProcessors(); private int numJobs = Runtime.getRuntime().availableProcessors();
/** The maximum number of trials. */
@Option(names = { "-m" }, paramLabel = "maxTrials", @Option(names = { "-m" }, paramLabel = "maxTrials",
description = "Maximal number of trials (default: ${DEFAULT-VALUE}).") description = "Maximal number of trials (default: ${DEFAULT-VALUE}).")
private int _maxTrials = 10; private int maxTrials = 10;
/** The output file. */
@Option(names = { "-o" }, paramLabel = "outputFile", required = true, @Option(names = { "-o" }, paramLabel = "outputFile", required = true,
description = "Output file name.") description = "Output file name.")
private String _outputFile = null; private String outputFile = null;
/** /**
* Program entry point. * Program entry point.
@ -62,7 +67,7 @@ public class StandAlone implements Callable<Void> {
} }
@Override @Override
public Void call() throws Exception { public Void call() throws FileNotFoundException, UnsupportedEncodingException {
// Cities (in optimal travel order). // Cities (in optimal travel order).
final City[] cities = new City[] { final City[] cities = new City[] {
new City("o0", 0, 0), new City("o0", 0, 0),
@ -87,11 +92,11 @@ public class StandAlone implements Callable<Void> {
double minDist = Double.POSITIVE_INFINITY; double minDist = Double.POSITIVE_INFINITY;
int count = 0; int count = 0;
while (count++ < _maxTrials) { while (count++ < maxTrials) {
final City[] travel = TravellingSalesmanSolver.solve(cities, final City[] travel = TravellingSalesmanSolver.solve(cities,
_neuronsPerCity, neuronsPerCity,
_numSamples, numSamples,
_numJobs, numJobs,
rng); rng);
final int numCities = City.unique(travel).size(); final int numCities = City.unique(travel).size();
if (numCities > maxCities) { if (numCities > maxCities) {
@ -108,7 +113,7 @@ public class StandAlone implements Callable<Void> {
} }
} }
printSummary(_outputFile, best, computeDistance(cities)); printSummary(outputFile, best, computeDistance(cities));
return null; return null;
} }
@ -146,8 +151,9 @@ public class StandAlone implements Callable<Void> {
*/ */
private static void printSummary(String fileName, private static void printSummary(String fileName,
City[] travel, City[] travel,
double optimalDistance) throws FileNotFoundException, UnsupportedEncodingException { double optimalDistance)
try (final PrintWriter out = new PrintWriter(fileName, StandardCharsets.UTF_8.name())) { throws FileNotFoundException, UnsupportedEncodingException {
try (PrintWriter out = new PrintWriter(fileName, StandardCharsets.UTF_8.name())) {
out.println("# Number of unique cities: " + City.unique(travel).size()); out.println("# Number of unique cities: " + City.unique(travel).size());
out.println("# Travel distance: " + computeDistance(travel)); out.println("# Travel distance: " + computeDistance(travel));
out.println("# Optimal travel distance: " + optimalDistance); out.println("# Optimal travel distance: " + optimalDistance);

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -51,7 +51,8 @@ import org.apache.commons.math4.neuralnet.sofm.LearningFactorFunction;
* "Travelling Salesman's Problem"</a> (i.e. trying to find the sequence of * "Travelling Salesman's Problem"</a> (i.e. trying to find the sequence of
* cities that minimizes the travel distance) using a 1D SOFM. * cities that minimizes the travel distance) using a 1D SOFM.
*/ */
public class TravellingSalesmanSolver { public final class TravellingSalesmanSolver {
/** The ID for the first neuron. */
private static final long FIRST_NEURON_ID = 0; private static final long FIRST_NEURON_ID = 0;
/** SOFM. */ /** SOFM. */
private final Network net; private final Network net;
@ -121,7 +122,7 @@ public class TravellingSalesmanSolver {
for (Future<?> f : execOutput) { for (Future<?> f : execOutput) {
f.get(); f.get();
} }
} catch (InterruptedException|ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
// Terminate all threads. // Terminate all threads.
@ -172,7 +173,7 @@ public class TravellingSalesmanSolver {
* in random order. * in random order.
* *
* @param numSamples Number of samples. * @param numSamples Number of samples.
* @param cities Cities. * @param uniqueCities Cities.
* @param random RNG. * @param random RNG.
* @return the iterator. * @return the iterator.
*/ */
@ -300,13 +301,13 @@ public class TravellingSalesmanSolver {
*/ */
class HarmonicOscillator implements DoubleUnaryOperator { class HarmonicOscillator implements DoubleUnaryOperator {
/** Amplitude. */ /** Amplitude. */
final double amplitude; private final double amplitude;
/** Angular speed. */ /** Angular speed. */
final double omega; private final double omega;
/** Phase. */ /** Phase. */
final double phase; private final double phase;
/** Offset. */ /** Offset. */
final double offset; private final double offset;
/** /**
* @param amplitude Amplitude. * @param amplitude Amplitude.
@ -314,10 +315,10 @@ class HarmonicOscillator implements DoubleUnaryOperator {
* @param phase Phase. * @param phase Phase.
* @param offset Offset (ordinate). * @param offset Offset (ordinate).
*/ */
public HarmonicOscillator(double amplitude, HarmonicOscillator(double amplitude,
double omega, double omega,
double phase, double phase,
double offset) { double offset) {
this.amplitude = amplitude; this.amplitude = amplitude;
this.omega = omega; this.omega = omega;
this.phase = phase; this.phase = phase;

View File

@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Traveling Salesman Problem.
*/
package org.apache.commons.math4.examples.sofm.tsp;

View File

@ -49,10 +49,8 @@ public interface FieldElement<T> {
T negate(); T negate();
/** Compute n &times; this. Multiplication by an integer number is defined /** Compute n &times; this. Multiplication by an integer number is defined
* as the following sum * as the following sum:
* <center> * <p>n &times; this = &sum;<sub>i=1</sub><sup>n</sup> this.
* n &times; this = &sum;<sub>i=1</sub><sup>n</sup> this.
* </center>
* @param n Number of times {@code this} must be added to itself. * @param n Number of times {@code this} must be added to itself.
* @return A new element representing n &times; this. * @return A new element representing n &times; this.
*/ */

View File

@ -29,7 +29,7 @@ import org.apache.commons.math4.legacy.exception.ZeroException;
* *
* @since 3.6 * @since 3.6
*/ */
public class IntegerSequence { public final class IntegerSequence {
/** /**
* Utility class contains only static methods. * Utility class contains only static methods.
*/ */
@ -128,7 +128,7 @@ public class IntegerSequence {
* custom {@link MaxCountExceededCallback callback}, in order to e.g. * custom {@link MaxCountExceededCallback callback}, in order to e.g.
* select which exception must be thrown. * select which exception must be thrown.
*/ */
public static class Incrementor implements Iterator<Integer> { public static final class Incrementor implements Iterator<Integer> {
/** Default callback. */ /** Default callback. */
private static final MaxCountExceededCallback CALLBACK private static final MaxCountExceededCallback CALLBACK
= new MaxCountExceededCallback() { = new MaxCountExceededCallback() {

View File

@ -18,12 +18,8 @@
package org.apache.commons.math4.legacy.core; package org.apache.commons.math4.legacy.core;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.TreeSet; import java.util.TreeSet;
import org.apache.commons.numbers.core.Precision; import org.apache.commons.numbers.core.Precision;
@ -46,7 +42,7 @@ import org.apache.commons.math4.legacy.core.jdkmath.AccurateMath;
* *
* @since 3.0 * @since 3.0
*/ */
public class MathArrays { public final class MathArrays {
/** /**
* Private constructor. * Private constructor.
@ -245,13 +241,13 @@ public class MathArrays {
* @throws DimensionMismatchException if the array lengths differ. * @throws DimensionMismatchException if the array lengths differ.
*/ */
public static double distance(int[] p1, int[] p2) { public static double distance(int[] p1, int[] p2) {
checkEqualLength(p1, p2); checkEqualLength(p1, p2);
double sum = 0; double sum = 0;
for (int i = 0; i < p1.length; i++) { for (int i = 0; i < p1.length; i++) {
final double dp = p1[i] - p2[i]; final double dp = p1[i] - p2[i];
sum += dp * dp; sum += dp * dp;
} }
return AccurateMath.sqrt(sum); return AccurateMath.sqrt(sum);
} }
/** /**
@ -335,7 +331,7 @@ public class MathArrays {
} }
} else { } else {
if (comp > 0) { if (comp > 0) {
return false; return false;
} }
} }
break; break;
@ -570,7 +566,7 @@ public class MathArrays {
* @since 3.4 * @since 3.4
*/ */
public static void checkNotNaN(final double[] in) { public static void checkNotNaN(final double[] in) {
for(int i = 0; i < in.length; i++) { for (int i = 0; i < in.length; i++) {
if (Double.isNaN(in[i])) { if (Double.isNaN(in[i])) {
throw new NotANumberException(); throw new NotANumberException();
} }
@ -600,7 +596,7 @@ public class MathArrays {
* @since 3.1 * @since 3.1
*/ */
public static void checkNonNegative(final long[][] in) { public static void checkNonNegative(final long[][] in) {
for (int i = 0; i < in.length; i ++) { for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) { for (int j = 0; j < in[i].length; j++) {
if (in[i][j] < 0) { if (in[i][j] < 0) {
throw new NotPositiveException(in[i][j]); throw new NotPositiveException(in[i][j]);
@ -620,7 +616,7 @@ public class MathArrays {
* and equal elements. * and equal elements.
*/ */
public static boolean equals(float[] x, float[] y) { public static boolean equals(float[] x, float[] y) {
if ((x == null) || (y == null)) { if (x == null || y == null) {
return !((x == null) ^ (y == null)); return !((x == null) ^ (y == null));
} }
if (x.length != y.length) { if (x.length != y.length) {
@ -646,7 +642,7 @@ public class MathArrays {
* @since 2.2 * @since 2.2
*/ */
public static boolean equalsIncludingNaN(float[] x, float[] y) { public static boolean equalsIncludingNaN(float[] x, float[] y) {
if ((x == null) || (y == null)) { if (x == null || y == null) {
return !((x == null) ^ (y == null)); return !((x == null) ^ (y == null));
} }
if (x.length != y.length) { if (x.length != y.length) {
@ -671,7 +667,7 @@ public class MathArrays {
* dimension and equal elements. * dimension and equal elements.
*/ */
public static boolean equals(double[] x, double[] y) { public static boolean equals(double[] x, double[] y) {
if ((x == null) || (y == null)) { if (x == null || y == null) {
return !((x == null) ^ (y == null)); return !((x == null) ^ (y == null));
} }
if (x.length != y.length) { if (x.length != y.length) {
@ -697,7 +693,7 @@ public class MathArrays {
* @since 2.2 * @since 2.2
*/ */
public static boolean equalsIncludingNaN(double[] x, double[] y) { public static boolean equalsIncludingNaN(double[] x, double[] y) {
if ((x == null) || (y == null)) { if (x == null || y == null) {
return !((x == null) ^ (y == null)); return !((x == null) ^ (y == null));
} }
if (x.length != y.length) { if (x.length != y.length) {
@ -1049,10 +1045,12 @@ public class MathArrays {
throw new MathIllegalArgumentException(LocalizedFormats.NAN_ELEMENT_AT_INDEX, Integer.valueOf(i)); throw new MathIllegalArgumentException(LocalizedFormats.NAN_ELEMENT_AT_INDEX, Integer.valueOf(i));
} }
if (Double.isInfinite(weight)) { if (Double.isInfinite(weight)) {
throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_ARRAY_ELEMENT, Double.valueOf(weight), Integer.valueOf(i)); throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_ARRAY_ELEMENT,
Double.valueOf(weight), Integer.valueOf(i));
} }
if (weight < 0) { if (weight < 0) {
throw new MathIllegalArgumentException(LocalizedFormats.NEGATIVE_ELEMENT_AT_INDEX, Integer.valueOf(i), Double.valueOf(weight)); throw new MathIllegalArgumentException(LocalizedFormats.NEGATIVE_ELEMENT_AT_INDEX,
Integer.valueOf(i), Double.valueOf(weight));
} }
if (!containsPositiveWeight && weight > 0.0) { if (!containsPositiveWeight && weight > 0.0) {
containsPositiveWeight = true; containsPositiveWeight = true;
@ -1077,7 +1075,7 @@ public class MathArrays {
* @throws NullPointerException if any of the arrays are null * @throws NullPointerException if any of the arrays are null
* @since 3.6 * @since 3.6
*/ */
public static double[] concatenate(double[] ...x) { public static double[] concatenate(double[]... x) {
int combinedLength = 0; int combinedLength = 0;
for (double[] a : x) { for (double[] a : x) {
combinedLength += a.length; combinedLength += a.length;

View File

@ -87,7 +87,8 @@ public interface RealFieldElement<T> extends FieldElement<T> {
*/ */
T floor(); T floor();
/** Get the whole number that is the nearest to the instance, or the even one if x is exactly half way between two integers. /** Get the whole number that is the nearest to the instance, or the even one if x is exactly
* half way between two integers.
* @return a double number r such that r is an integer r - 0.5 &le; this &le; r + 0.5 * @return a double number r such that r is an integer r - 0.5 &le; this &le; r + 0.5
*/ */
T rint(); T rint();
@ -405,7 +406,7 @@ public interface RealFieldElement<T> extends FieldElement<T> {
* @param e2 second element * @param e2 second element
* @return max(a1, e2) * @return max(a1, e2)
*/ */
public static <T extends RealFieldElement<T>> T max(final T e1, final T e2) { static <T extends RealFieldElement<T>> T max(final T e1, final T e2) {
return e1.subtract(e2).getReal() >= 0 ? e1 : e2; return e1.subtract(e2).getReal() >= 0 ? e1 : e2;
} }
@ -415,7 +416,7 @@ public interface RealFieldElement<T> extends FieldElement<T> {
* @param e2 second element * @param e2 second element
* @return min(a1, e2) * @return min(a1, e2)
*/ */
public static <T extends RealFieldElement<T>> T min(final T e1, final T e2) { static <T extends RealFieldElement<T>> T min(final T e1, final T e2) {
return e1.subtract(e2).getReal() >= 0 ? e2 : e1; return e1.subtract(e2).getReal() >= 0 ? e2 : e1;
} }
} }

View File

@ -163,7 +163,7 @@ public class DfpDec extends Dfp {
@Override @Override
protected int round(int in) { protected int round(int in) {
int msb = mant[mant.length-1]; int msb = mant[mant.length - 1];
if (msb == 0) { if (msb == 0) {
// special case -- this == zero // special case -- this == zero
return 0; return 0;
@ -173,7 +173,7 @@ public class DfpDec extends Dfp {
int lsbthreshold = 1000; int lsbthreshold = 1000;
while (lsbthreshold > msb) { while (lsbthreshold > msb) {
lsbthreshold /= 10; lsbthreshold /= 10;
cmaxdigits --; cmaxdigits--;
} }
@ -196,12 +196,12 @@ public class DfpDec extends Dfp {
final int n; final int n;
if (lsbthreshold == 1) { if (lsbthreshold == 1) {
// look to the next digit for rounding // look to the next digit for rounding
n = (mant[lsd-1] / 1000) % 10; n = (mant[lsd - 1] / 1000) % 10;
mant[lsd-1] %= 1000; mant[lsd - 1] %= 1000;
discarded |= mant[lsd-1]; discarded |= mant[lsd - 1];
} else { } else {
n = (lsb * 10 / lsbthreshold) % 10; n = (lsb * 10 / lsbthreshold) % 10;
discarded |= lsb % (lsbthreshold/10); discarded |= lsb % (lsbthreshold / 10);
} }
for (int i = 0; i < lsd; i++) { for (int i = 0; i < lsd; i++) {
@ -213,42 +213,42 @@ public class DfpDec extends Dfp {
final boolean inc; final boolean inc;
switch (getField().getRoundingMode()) { switch (getField().getRoundingMode()) {
case ROUND_DOWN: case ROUND_DOWN:
inc = false; inc = false;
break; break;
case ROUND_UP: case ROUND_UP:
inc = (n != 0) || (discarded != 0); // round up if n!=0 inc = (n != 0) || (discarded != 0); // round up if n!=0
break; break;
case ROUND_HALF_UP: case ROUND_HALF_UP:
inc = n >= 5; // round half up inc = n >= 5; // round half up
break; break;
case ROUND_HALF_DOWN: case ROUND_HALF_DOWN:
inc = n > 5; // round half down inc = n > 5; // round half down
break; break;
case ROUND_HALF_EVEN: case ROUND_HALF_EVEN:
inc = (n > 5) || inc = (n > 5) ||
(n == 5 && discarded != 0) || (n == 5 && discarded != 0) ||
(n == 5 && discarded == 0 && ((lsb / lsbthreshold) & 1) == 1); // round half-even (n == 5 && discarded == 0 && ((lsb / lsbthreshold) & 1) == 1); // round half-even
break; break;
case ROUND_HALF_ODD: case ROUND_HALF_ODD:
inc = (n > 5) || inc = (n > 5) ||
(n == 5 && discarded != 0) || (n == 5 && discarded != 0) ||
(n == 5 && discarded == 0 && ((lsb / lsbthreshold) & 1) == 0); // round half-odd (n == 5 && discarded == 0 && ((lsb / lsbthreshold) & 1) == 0); // round half-odd
break; break;
case ROUND_CEIL: case ROUND_CEIL:
inc = (sign == 1) && (n != 0 || discarded != 0); // round ceil inc = (sign == 1) && (n != 0 || discarded != 0); // round ceil
break; break;
case ROUND_FLOOR: case ROUND_FLOOR:
default: default:
inc = (sign == -1) && (n != 0 || discarded != 0); // round floor inc = (sign == -1) && (n != 0 || discarded != 0); // round floor
break; break;
} }
if (inc) { if (inc) {
@ -262,7 +262,7 @@ public class DfpDec extends Dfp {
if (rh != 0) { if (rh != 0) {
shiftRight(); shiftRight();
mant[mant.length-1]=rh; mant[mant.length - 1] = rh;
} }
} }
@ -323,7 +323,7 @@ public class DfpDec extends Dfp {
inc = copysign(inc, this); inc = copysign(inc, this);
if (this.equals(getZero())) { if (this.equals(getZero())) {
inc = power10K(MIN_EXP-mant.length-1); inc = power10K(MIN_EXP - mant.length - 1);
} }
if (inc.equals(getZero())) { if (inc.equals(getZero())) {
@ -342,7 +342,7 @@ public class DfpDec extends Dfp {
} }
if (this.equals(getZero())) { if (this.equals(getZero())) {
inc = power10K(MIN_EXP-mant.length-1); inc = power10K(MIN_EXP - mant.length - 1);
} }
if (inc.equals(getZero())) { if (inc.equals(getZero())) {
@ -357,7 +357,7 @@ public class DfpDec extends Dfp {
result = dotrap(DfpField.FLAG_INEXACT, trapName, x, result); result = dotrap(DfpField.FLAG_INEXACT, trapName, x, result);
} }
if (result.equals(getZero()) && this.equals(getZero()) == false) { if (result.equals(getZero()) && !this.equals(getZero())) {
getField().setIEEEFlagsBits(DfpField.FLAG_INEXACT); getField().setIEEEFlagsBits(DfpField.FLAG_INEXACT);
result = dotrap(DfpField.FLAG_INEXACT, trapName, x, result); result = dotrap(DfpField.FLAG_INEXACT, trapName, x, result);
} }

View File

@ -529,48 +529,47 @@ public class DfpField implements Field<Dfp> {
* @return an array of two {@link Dfp Dfp} instances which sum equals a * @return an array of two {@link Dfp Dfp} instances which sum equals a
*/ */
private Dfp[] split(final String a) { private Dfp[] split(final String a) {
Dfp result[] = new Dfp[2]; Dfp[] result = new Dfp[2];
boolean leading = true; boolean leading = true;
int sp = 0; int sp = 0;
int sig = 0; int sig = 0;
char[] buf = new char[a.length()]; char[] buf = new char[a.length()];
for (int i = 0; i < buf.length; i++) { for (int i = 0; i < buf.length; i++) {
buf[i] = a.charAt(i); buf[i] = a.charAt(i);
if (buf[i] >= '1' && buf[i] <= '9') { if (buf[i] >= '1' && buf[i] <= '9') {
leading = false; leading = false;
}
if (buf[i] == '.') {
sig += (400 - sig) % 4;
leading = false;
}
if (sig == (radixDigits / 2) * 4) {
sp = i;
break;
}
if (buf[i] >= '0' && buf[i] <= '9' && !leading) {
sig++;
}
} }
if (buf[i] == '.') { result[0] = new Dfp(this, String.valueOf(buf, 0, sp));
sig += (400 - sig) % 4;
leading = false; for (int i = 0; i < buf.length; i++) {
buf[i] = a.charAt(i);
if (buf[i] >= '0' && buf[i] <= '9' && i < sp) {
buf[i] = '0';
}
} }
if (sig == (radixDigits / 2) * 4) { result[1] = new Dfp(this, String.valueOf(buf));
sp = i;
break;
}
if (buf[i] >= '0' && buf[i] <= '9' && !leading) {
sig ++;
}
}
result[0] = new Dfp(this, new String(buf, 0, sp));
for (int i = 0; i < buf.length; i++) {
buf[i] = a.charAt(i);
if (buf[i] >= '0' && buf[i] <= '9' && i < sp) {
buf[i] = '0';
}
}
result[1] = new Dfp(this, new String(buf));
return result;
return result;
} }
/** Recompute the high precision string constants. /** Recompute the high precision string constants.

View File

@ -21,7 +21,7 @@ package org.apache.commons.math4.legacy.core.dfp;
* The constants are defined in {@link DfpField} * The constants are defined in {@link DfpField}
* @since 2.2 * @since 2.2
*/ */
public class DfpMath { public final class DfpMath {
/** Name for traps triggered by pow. */ /** Name for traps triggered by pow. */
private static final String POW_TRAP = "pow"; private static final String POW_TRAP = "pow";
@ -42,7 +42,7 @@ public class DfpMath {
* @return an array of two {@link Dfp} which sum is a * @return an array of two {@link Dfp} which sum is a
*/ */
protected static Dfp[] split(final DfpField field, final String a) { protected static Dfp[] split(final DfpField field, final String a) {
Dfp result[] = new Dfp[2]; Dfp[] result = new Dfp[2];
char[] buf; char[] buf;
boolean leading = true; boolean leading = true;
int sp = 0; int sp = 0;
@ -68,11 +68,11 @@ public class DfpMath {
} }
if (buf[i] >= '0' && buf[i] <= '9' && !leading) { if (buf[i] >= '0' && buf[i] <= '9' && !leading) {
sig ++; sig++;
} }
} }
result[0] = field.newDfp(new String(buf, 0, sp)); result[0] = field.newDfp(String.valueOf(buf, 0, sp));
for (int i = 0; i < buf.length; i++) { for (int i = 0; i < buf.length; i++) {
buf[i] = a.charAt(i); buf[i] = a.charAt(i);
@ -81,7 +81,7 @@ public class DfpMath {
} }
} }
result[1] = field.newDfp(new String(buf)); result[1] = field.newDfp(String.valueOf(buf));
return result; return result;
} }
@ -199,7 +199,6 @@ public class DfpMath {
} }
return result[0]; return result[0];
} }
/** Raises base to the power a by successive squaring. /** Raises base to the power a by successive squaring.
@ -207,8 +206,7 @@ public class DfpMath {
* @param a power * @param a power
* @return base<sup>a</sup> * @return base<sup>a</sup>
*/ */
public static Dfp pow(Dfp base, int a) public static Dfp pow(Dfp base, int a) {
{
boolean invert = false; boolean invert = false;
Dfp result = base.getOne(); Dfp result = base.getOne();
@ -235,7 +233,7 @@ public class DfpMath {
prevtrial = trial; prevtrial = trial;
r = r.multiply(r); r = r.multiply(r);
trial *= 2; trial *= 2;
} while (a>trial); } while (a > trial);
r = prevr; r = prevr;
trial = prevtrial; trial = prevtrial;
@ -250,7 +248,6 @@ public class DfpMath {
} }
return base.newInstance(result); return base.newInstance(result);
} }
/** Computes e to the given power. /** Computes e to the given power.
@ -359,14 +356,14 @@ public class DfpMath {
// X is now in the range of 2/3 < x < 4/3 // X is now in the range of 2/3 < x < 4/3
Dfp[] spz = logInternal(spx); Dfp[] spz = logInternal(spx);
spx[0] = a.newInstance(new StringBuilder().append(p2+4*lr).toString()); spx[0] = a.newInstance(new StringBuilder().append(p2 + 4 * lr).toString());
spx[1] = a.getZero(); spx[1] = a.getZero();
spy = splitMult(a.getField().getLn2Split(), spx); spy = splitMult(a.getField().getLn2Split(), spx);
spz[0] = spz[0].add(spy[0]); spz[0] = spz[0].add(spy[0]);
spz[1] = spz[1].add(spy[1]); spz[1] = spz[1].add(spy[1]);
spx[0] = a.newInstance(new StringBuilder().append(4*lr).toString()); spx[0] = a.newInstance(new StringBuilder().append(4 * lr).toString());
spx[1] = a.getZero(); spx[1] = a.getZero();
spy = splitMult(a.getField().getLn5Split(), spx); spy = splitMult(a.getField().getLn5Split(), spx);
@ -374,7 +371,6 @@ public class DfpMath {
spz[1] = spz[1].add(spy[1]); spz[1] = spz[1].add(spy[1]);
return a.newInstance(spz[0].add(spz[1])); return a.newInstance(spz[0].add(spz[1]));
} }
/** Computes the natural log of a number between 0 and 2. /** Computes the natural log of a number between 0 and 2.
@ -434,7 +430,7 @@ public class DfpMath {
* @param a number from which logarithm is requested, in split form * @param a number from which logarithm is requested, in split form
* @return log(a) * @return log(a)
*/ */
protected static Dfp[] logInternal(final Dfp a[]) { protected static Dfp[] logInternal(final Dfp[] a) {
/* Now we want to compute x = (a-1)/(a+1) but this is prone to /* Now we want to compute x = (a-1)/(a+1) but this is prone to
* loss of precision. So instead, compute x = (a/4 - 1/4) / (a/4 + 1/4) * loss of precision. So instead, compute x = (a/4 - 1/4) / (a/4 + 1/4)
@ -669,7 +665,7 @@ public class DfpMath {
* @param a number from which sine is desired, in split form * @param a number from which sine is desired, in split form
* @return sin(a) * @return sin(a)
*/ */
protected static Dfp sinInternal(Dfp a[]) { protected static Dfp sinInternal(Dfp[] a) {
Dfp c = a[0].add(a[1]); Dfp c = a[0].add(a[1]);
Dfp y = c; Dfp y = c;
@ -682,7 +678,7 @@ public class DfpMath {
x = x.multiply(c); x = x.multiply(c);
x = x.negate(); x = x.negate();
fact = fact.divide((i-1)*i); // 1 over fact fact = fact.divide((i - 1) * i); // 1 over fact
y = y.add(x.multiply(fact)); y = y.add(x.multiply(fact));
if (y.equals(py)) { if (y.equals(py)) {
break; break;
@ -699,7 +695,7 @@ public class DfpMath {
* @param a number from which cosine is desired, in split form * @param a number from which cosine is desired, in split form
* @return cos(a) * @return cos(a)
*/ */
protected static Dfp cosInternal(Dfp a[]) { protected static Dfp cosInternal(Dfp[] a) {
final Dfp one = a[0].getOne(); final Dfp one = a[0].getOne();
@ -759,7 +755,7 @@ public class DfpMath {
if (x.lessThan(pi.divide(4))) { if (x.lessThan(pi.divide(4))) {
y = sinInternal(split(x)); y = sinInternal(split(x));
} else { } else {
final Dfp c[] = new Dfp[2]; final Dfp[] c = new Dfp[2];
final Dfp[] piSplit = a.getField().getPiSplit(); final Dfp[] piSplit = a.getField().getPiSplit();
c[0] = piSplit[0].divide(2).subtract(x); c[0] = piSplit[0].divide(2).subtract(x);
c[1] = piSplit[1].divide(2); c[1] = piSplit[1].divide(2);
@ -803,13 +799,13 @@ public class DfpMath {
Dfp y; Dfp y;
if (x.lessThan(pi.divide(4))) { if (x.lessThan(pi.divide(4))) {
Dfp c[] = new Dfp[2]; Dfp[] c = new Dfp[2];
c[0] = x; c[0] = x;
c[1] = zero; c[1] = zero;
y = cosInternal(c); y = cosInternal(c);
} else { } else {
final Dfp c[] = new Dfp[2]; final Dfp[] c = new Dfp[2];
final Dfp[] piSplit = a.getField().getPiSplit(); final Dfp[] piSplit = a.getField().getPiSplit();
c[0] = piSplit[0].divide(2).subtract(x); c[0] = piSplit[0].divide(2).subtract(x);
c[1] = piSplit[1].divide(2); c[1] = piSplit[1].divide(2);
@ -857,7 +853,7 @@ public class DfpMath {
} }
/** computes the arc tangent of the argument /** Computes the arc tangent of the argument.
* *
* Uses the typical taylor series * Uses the typical taylor series
* *
@ -893,7 +889,7 @@ public class DfpMath {
} }
if (x.greaterThan(ty)) { if (x.greaterThan(ty)) {
Dfp sty[] = new Dfp[2]; Dfp[] sty = new Dfp[2];
sub = true; sub = true;
sty[0] = sqr2Split[0].subtract(one); sty[0] = sqr2Split[0].subtract(one);

View File

@ -23,7 +23,7 @@ import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
/** Class used to compute the classical functions tables. /** Class used to compute the classical functions tables.
* @since 3.0 * @since 3.0
*/ */
class AccurateMathCalc { final class AccurateMathCalc {
/** /**
* 0x40000000 - used to split a double into two parts, both with the low order bits cleared. * 0x40000000 - used to split a double into two parts, both with the low order bits cleared.
@ -32,7 +32,7 @@ class AccurateMathCalc {
private static final long HEX_40000000 = 0x40000000L; // 1073741824L private static final long HEX_40000000 = 0x40000000L; // 1073741824L
/** Factorial table, for Taylor series expansions. 0!, 1!, 2!, ... 19! */ /** Factorial table, for Taylor series expansions. 0!, 1!, 2!, ... 19! */
private static final double FACT[] = new double[] private static final double[] FACT = new double[]
{ {
+1.0d, // 0 +1.0d, // 0
+1.0d, // 1 +1.0d, // 1
@ -57,7 +57,7 @@ class AccurateMathCalc {
}; };
/** Coefficients for slowLog. */ /** Coefficients for slowLog. */
private static final double LN_SPLIT_COEF[][] = { private static final double[][] LN_SPLIT_COEF = {
{2.0, 0.0}, {2.0, 0.0},
{0.6666666269302368, 3.9736429850260626E-8}, {0.6666666269302368, 3.9736429850260626E-8},
{0.3999999761581421, 2.3841857910019882E-8}, {0.3999999761581421, 2.3841857910019882E-8},
@ -101,7 +101,7 @@ class AccurateMathCalc {
private static void buildSinCosTables(double[] SINE_TABLE_A, double[] SINE_TABLE_B, private static void buildSinCosTables(double[] SINE_TABLE_A, double[] SINE_TABLE_B,
double[] COSINE_TABLE_A, double[] COSINE_TABLE_B, double[] COSINE_TABLE_A, double[] COSINE_TABLE_B,
int SINE_TABLE_LEN, double[] TANGENT_TABLE_A, double[] TANGENT_TABLE_B) { int SINE_TABLE_LEN, double[] TANGENT_TABLE_A, double[] TANGENT_TABLE_B) {
final double result[] = new double[2]; final double[] result = new double[2];
/* Use taylor series for 0 <= x <= 6/8 */ /* Use taylor series for 0 <= x <= 6/8 */
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
@ -118,18 +118,18 @@ class AccurateMathCalc {
/* Use angle addition formula to complete table to 13/8, just beyond pi/2 */ /* Use angle addition formula to complete table to 13/8, just beyond pi/2 */
for (int i = 7; i < SINE_TABLE_LEN; i++) { for (int i = 7; i < SINE_TABLE_LEN; i++) {
double xs[] = new double[2]; double[] xs = new double[2];
double ys[] = new double[2]; double[] ys = new double[2];
double as[] = new double[2]; double[] as = new double[2];
double bs[] = new double[2]; double[] bs = new double[2];
double temps[] = new double[2]; double[] temps = new double[2];
if ( (i & 1) == 0) { if ((i & 1) == 0) {
// Even, use double angle // Even, use double angle
xs[0] = SINE_TABLE_A[i/2]; xs[0] = SINE_TABLE_A[i / 2];
xs[1] = SINE_TABLE_B[i/2]; xs[1] = SINE_TABLE_B[i / 2];
ys[0] = COSINE_TABLE_A[i/2]; ys[0] = COSINE_TABLE_A[i / 2];
ys[1] = COSINE_TABLE_B[i/2]; ys[1] = COSINE_TABLE_B[i / 2];
/* compute sine */ /* compute sine */
splitMult(xs, ys, result); splitMult(xs, ys, result);
@ -145,14 +145,14 @@ class AccurateMathCalc {
COSINE_TABLE_A[i] = result[0]; COSINE_TABLE_A[i] = result[0];
COSINE_TABLE_B[i] = result[1]; COSINE_TABLE_B[i] = result[1];
} else { } else {
xs[0] = SINE_TABLE_A[i/2]; xs[0] = SINE_TABLE_A[i / 2];
xs[1] = SINE_TABLE_B[i/2]; xs[1] = SINE_TABLE_B[i / 2];
ys[0] = COSINE_TABLE_A[i/2]; ys[0] = COSINE_TABLE_A[i / 2];
ys[1] = COSINE_TABLE_B[i/2]; ys[1] = COSINE_TABLE_B[i / 2];
as[0] = SINE_TABLE_A[i/2+1]; as[0] = SINE_TABLE_A[i / 2 + 1];
as[1] = SINE_TABLE_B[i/2+1]; as[1] = SINE_TABLE_B[i / 2 + 1];
bs[0] = COSINE_TABLE_A[i/2+1]; bs[0] = COSINE_TABLE_A[i / 2 + 1];
bs[1] = COSINE_TABLE_B[i/2+1]; bs[1] = COSINE_TABLE_B[i / 2 + 1];
/* compute sine */ /* compute sine */
splitMult(xs, bs, temps); splitMult(xs, bs, temps);
@ -174,9 +174,9 @@ class AccurateMathCalc {
/* Compute tangent = sine/cosine */ /* Compute tangent = sine/cosine */
for (int i = 0; i < SINE_TABLE_LEN; i++) { for (int i = 0; i < SINE_TABLE_LEN; i++) {
double xs[] = new double[2]; double[] xs = new double[2];
double ys[] = new double[2]; double[] ys = new double[2];
double as[] = new double[2]; double[] as = new double[2];
as[0] = COSINE_TABLE_A[i]; as[0] = COSINE_TABLE_A[i];
as[1] = COSINE_TABLE_B[i]; as[1] = COSINE_TABLE_B[i];
@ -191,7 +191,6 @@ class AccurateMathCalc {
TANGENT_TABLE_A[i] = as[0]; TANGENT_TABLE_A[i] = as[0];
TANGENT_TABLE_B[i] = as[1]; TANGENT_TABLE_B[i] = as[1];
} }
} }
/** /**
@ -202,27 +201,28 @@ class AccurateMathCalc {
* (may be null) * (may be null)
* @return cos(x) * @return cos(x)
*/ */
static double slowCos(final double x, final double result[]) { static double slowCos(final double x, final double[] result) {
final double xs[] = new double[2]; final double[] xs = new double[2];
final double ys[] = new double[2]; final double[] ys = new double[2];
final double facts[] = new double[2]; final double[] facts = new double[2];
final double as[] = new double[2]; final double[] as = new double[2];
split(x, xs); split(x, xs);
ys[0] = ys[1] = 0.0; ys[0] = ys[1] = 0.0;
for (int i = FACT.length-1; i >= 0; i--) { for (int i = FACT.length - 1; i >= 0; i--) {
splitMult(xs, ys, as); splitMult(xs, ys, as);
ys[0] = as[0]; ys[1] = as[1]; ys[0] = as[0];
ys[1] = as[1];
if ( (i & 1) != 0) { // skip odd entries if ((i & 1) != 0) { // skip odd entries
continue; continue;
} }
split(FACT[i], as); split(FACT[i], as);
splitReciprocal(as, facts); splitReciprocal(as, facts);
if ( (i & 2) != 0 ) { // alternate terms are negative if ((i & 2) != 0) { // alternate terms are negative
facts[0] = -facts[0]; facts[0] = -facts[0];
facts[1] = -facts[1]; facts[1] = -facts[1];
} }
@ -247,26 +247,27 @@ class AccurateMathCalc {
* (may be null) * (may be null)
* @return sin(x) * @return sin(x)
*/ */
static double slowSin(final double x, final double result[]) { static double slowSin(final double x, final double[] result) {
final double xs[] = new double[2]; final double[] xs = new double[2];
final double ys[] = new double[2]; final double[] ys = new double[2];
final double facts[] = new double[2]; final double[] facts = new double[2];
final double as[] = new double[2]; final double[] as = new double[2];
split(x, xs); split(x, xs);
ys[0] = ys[1] = 0.0; ys[0] = ys[1] = 0.0;
for (int i = FACT.length-1; i >= 0; i--) { for (int i = FACT.length - 1; i >= 0; i--) {
splitMult(xs, ys, as); splitMult(xs, ys, as);
ys[0] = as[0]; ys[1] = as[1]; ys[0] = as[0];
ys[1] = as[1];
if ( (i & 1) == 0) { // Ignore even numbers if ((i & 1) == 0) { // Ignore even numbers
continue; continue;
} }
split(FACT[i], as); split(FACT[i], as);
splitReciprocal(as, facts); splitReciprocal(as, facts);
if ( (i & 2) != 0 ) { // alternate terms are negative if ((i & 2) != 0) { // alternate terms are negative
facts[0] = -facts[0]; facts[0] = -facts[0];
facts[1] = -facts[1]; facts[1] = -facts[1];
} }
@ -285,21 +286,21 @@ class AccurateMathCalc {
/** /**
* For x between 0 and 1, returns exp(x), uses extended precision * For x between 0 and 1, returns exp(x), uses extended precision.
* @param x argument of exponential * @param x argument of exponential
* @param result placeholder where to place exp(x) split in two terms * @param result placeholder where to place exp(x) split in two terms
* for extra precision (i.e. exp(x) = result[0] + result[1] * for extra precision (i.e. exp(x) = result[0] + result[1]
* @return exp(x) * @return exp(x)
*/ */
static double slowexp(final double x, final double result[]) { static double slowexp(final double x, final double[] result) {
final double xs[] = new double[2]; final double[] xs = new double[2];
final double ys[] = new double[2]; final double[] ys = new double[2];
final double facts[] = new double[2]; final double[] facts = new double[2];
final double as[] = new double[2]; final double[] as = new double[2];
split(x, xs); split(x, xs);
ys[0] = ys[1] = 0.0; ys[0] = ys[1] = 0.0;
for (int i = FACT.length-1; i >= 0; i--) { for (int i = FACT.length - 1; i >= 0; i--) {
splitMult(xs, ys, as); splitMult(xs, ys, as);
ys[0] = as[0]; ys[0] = as[0];
ys[1] = as[1]; ys[1] = as[1];
@ -325,7 +326,7 @@ class AccurateMathCalc {
* @param d number to split * @param d number to split
* @param split placeholder where to place the result * @param split placeholder where to place the result
*/ */
private static void split(final double d, final double split[]) { private static void split(final double d, final double[] split) {
if (d < 8e298 && d > -8e298) { if (d < 8e298 && d > -8e298) {
final double a = d * HEX_40000000; final double a = d * HEX_40000000;
split[0] = (d + a) - a; split[0] = (d + a) - a;
@ -341,7 +342,7 @@ class AccurateMathCalc {
* @param a input/out array containing the split, changed * @param a input/out array containing the split, changed
* on output * on output
*/ */
private static void resplit(final double a[]) { private static void resplit(final double[] a) {
final double c = a[0] + a[1]; final double c = a[0] + a[1];
final double d = -(c - a[0] - a[1]); final double d = -(c - a[0] - a[1]);
@ -361,7 +362,7 @@ class AccurateMathCalc {
* @param b second term of multiplication * @param b second term of multiplication
* @param ans placeholder where to put the result * @param ans placeholder where to put the result
*/ */
private static void splitMult(double a[], double b[], double ans[]) { private static void splitMult(double[] a, double[] b, double[] ans) {
ans[0] = a[0] * b[0]; ans[0] = a[0] * b[0];
ans[1] = a[0] * b[1] + a[1] * b[0] + a[1] * b[1]; ans[1] = a[0] * b[1] + a[1] * b[0] + a[1] * b[1];
@ -374,7 +375,7 @@ class AccurateMathCalc {
* @param b second term of addition * @param b second term of addition
* @param ans placeholder where to put the result * @param ans placeholder where to put the result
*/ */
private static void splitAdd(final double a[], final double b[], final double ans[]) { private static void splitAdd(final double[] a, final double[] b, final double[] ans) {
ans[0] = a[0] + b[0]; ans[0] = a[0] + b[0];
ans[1] = a[1] + b[1]; ans[1] = a[1] + b[1];
@ -399,8 +400,8 @@ class AccurateMathCalc {
* @param in initial number, in split form * @param in initial number, in split form
* @param result placeholder where to put the result * @param result placeholder where to put the result
*/ */
static void splitReciprocal(final double in[], final double result[]) { static void splitReciprocal(final double[] in, final double[] result) {
final double b = 1.0/4194304.0; final double b = 1.0 / 4194304.0;
final double a = 1.0 - b; final double a = 1.0 - b;
if (in[0] == 0.0) { if (in[0] == 0.0) {
@ -409,7 +410,7 @@ class AccurateMathCalc {
} }
result[0] = a / in[0]; result[0] = a / in[0];
result[1] = (b*in[0]-a*in[1]) / (in[0]*in[0] + in[0]*in[1]); result[1] = (b * in[0] - a * in[1]) / (in[0] * in[0] + in[0] * in[1]);
if (result[1] != result[1]) { // can happen if result[1] is NAN if (result[1] != result[1]) { // can happen if result[1] is NAN
result[1] = 0.0; result[1] = 0.0;
@ -421,7 +422,7 @@ class AccurateMathCalc {
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
/* this may be overkill, probably once is enough */ /* this may be overkill, probably once is enough */
double err = 1.0 - result[0] * in[0] - result[0] * in[1] - double err = 1.0 - result[0] * in[0] - result[0] * in[1] -
result[1] * in[0] - result[1] * in[1]; result[1] * in[0] - result[1] * in[1];
/*err = 1.0 - err; */ /*err = 1.0 - err; */
err *= result[0] + result[1]; err *= result[0] + result[1];
/*printf("err = %16e\n", err); */ /*printf("err = %16e\n", err); */
@ -434,10 +435,10 @@ class AccurateMathCalc {
* @param b second term of the multiplication * @param b second term of the multiplication
* @param result placeholder where to put the result * @param result placeholder where to put the result
*/ */
private static void quadMult(final double a[], final double b[], final double result[]) { private static void quadMult(final double[] a, final double[] b, final double[] result) {
final double xs[] = new double[2]; final double[] xs = new double[2];
final double ys[] = new double[2]; final double[] ys = new double[2];
final double zs[] = new double[2]; final double[] zs = new double[2];
/* a[0] * b[0] */ /* a[0] * b[0] */
split(a[0], xs); split(a[0], xs);
@ -488,11 +489,11 @@ class AccurateMathCalc {
* @param result placeholder where to put the result in extended precision * @param result placeholder where to put the result in extended precision
* @return exp(p) in standard precision (equal to result[0] + result[1]) * @return exp(p) in standard precision (equal to result[0] + result[1])
*/ */
static double expint(int p, final double result[]) { static double expint(int p, final double[] result) {
//double x = M_E; //double x = M_E;
final double xs[] = new double[2]; final double[] xs = new double[2];
final double as[] = new double[2]; final double[] as = new double[2];
final double ys[] = new double[2]; final double[] ys = new double[2];
//split(x, xs); //split(x, xs);
//xs[1] = (double)(2.7182818284590452353602874713526625L - xs[0]); //xs[1] = (double)(2.7182818284590452353602874713526625L - xs[0]);
//xs[0] = 2.71827697753906250000; //xs[0] = 2.71827697753906250000;
@ -547,10 +548,10 @@ class AccurateMathCalc {
* @return log(xi) * @return log(xi)
*/ */
static double[] slowLog(double xi) { static double[] slowLog(double xi) {
double x[] = new double[2]; double[] x = new double[2];
double x2[] = new double[2]; double[] x2 = new double[2];
double y[] = new double[2]; double[] y = new double[2];
double a[] = new double[2]; double[] a = new double[2];
split(xi, x); split(xi, x);
@ -571,10 +572,10 @@ class AccurateMathCalc {
//x[0] -= 1.0; //x[0] -= 1.0;
//resplit(x); //resplit(x);
y[0] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][0]; y[0] = LN_SPLIT_COEF[LN_SPLIT_COEF.length - 1][0];
y[1] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][1]; y[1] = LN_SPLIT_COEF[LN_SPLIT_COEF.length - 1][1];
for (int i = LN_SPLIT_COEF.length-2; i >= 0; i--) { for (int i = LN_SPLIT_COEF.length - 2; i >= 0; i--) {
splitMult(y, x2, a); splitMult(y, x2, a);
y[0] = a[0]; y[0] = a[0];
y[1] = a[1]; y[1] = a[1];
@ -603,9 +604,9 @@ class AccurateMathCalc {
checkLen(expectedLen, array2d.length); checkLen(expectedLen, array2d.length);
out.println(TABLE_START_DECL + " "); out.println(TABLE_START_DECL + " ");
int i = 0; int i = 0;
for(double[] array : array2d) { // "double array[]" causes PMD parsing error for (double[] array : array2d) { // "double array[]" causes PMD parsing error
out.print(" {"); out.print(" {");
for(double d : array) { // assume inner array has very few entries for (double d : array) { // assume inner array has very few entries
out.printf("%-25.25s", format(d)); // multiple entries per line out.printf("%-25.25s", format(d)); // multiple entries per line
} }
out.println("}, // " + i++); out.println("}, // " + i++);
@ -624,7 +625,7 @@ class AccurateMathCalc {
out.println(name + "="); out.println(name + "=");
checkLen(expectedLen, array.length); checkLen(expectedLen, array.length);
out.println(TABLE_START_DECL); out.println(TABLE_START_DECL);
for(double d : array){ for (double d : array) {
out.printf(" %s%n", format(d)); // one entry per line out.printf(" %s%n", format(d)); // one entry per line
} }
out.println(TABLE_END_DECL); out.println(TABLE_END_DECL);
@ -654,5 +655,4 @@ class AccurateMathCalc {
throw new DimensionMismatchException(actual, expectedLen); throw new DimensionMismatchException(actual, expectedLen);
} }
} }
} }

View File

@ -0,0 +1,21 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Portable alternative to {@link java.lang.Math} and {@link java.lang.StrictMath}.
*/
package org.apache.commons.math4.legacy.core.jdkmath;

View File

@ -0,0 +1,21 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Core math utilities.
*/
package org.apache.commons.math4.legacy.core;

View File

@ -104,7 +104,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
public void testDivideDouble() { public void testDivideDouble() {
for (double x = -3; x < 3; x += 0.2) { for (double x = -3; x < 3; x += 0.2) {
for (double y = -3; y < 3; y += 0.2) { for (double y = -3; y < 3; y += 0.2) {
checkRelative(x / y, build(x).divide(y)); checkRelative(x / y, build(x).divide(y));
} }
} }
} }
@ -391,7 +391,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationFaFa() { public void testLinearCombinationFaFa() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xfafal); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xfafaL);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 10); double[] aD = generateDouble(r, 10);
double[] bD = generateDouble(r, 10); double[] bD = generateDouble(r, 10);
@ -404,7 +404,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationDaFa() { public void testLinearCombinationDaFa() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdafal); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdafaL);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 10); double[] aD = generateDouble(r, 10);
double[] bD = generateDouble(r, 10); double[] bD = generateDouble(r, 10);
@ -416,7 +416,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationFF2() { public void testLinearCombinationFF2() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff2l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff2L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 2); double[] aD = generateDouble(r, 2);
double[] bD = generateDouble(r, 2); double[] bD = generateDouble(r, 2);
@ -431,7 +431,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationDF2() { public void testLinearCombinationDF2() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf2l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf2L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 2); double[] aD = generateDouble(r, 2);
double[] bD = generateDouble(r, 2); double[] bD = generateDouble(r, 2);
@ -445,7 +445,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationFF3() { public void testLinearCombinationFF3() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff3l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff3L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 3); double[] aD = generateDouble(r, 3);
double[] bD = generateDouble(r, 3); double[] bD = generateDouble(r, 3);
@ -461,7 +461,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationDF3() { public void testLinearCombinationDF3() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf3l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf3L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 3); double[] aD = generateDouble(r, 3);
double[] bD = generateDouble(r, 3); double[] bD = generateDouble(r, 3);
@ -476,7 +476,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationFF4() { public void testLinearCombinationFF4() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff4l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xff4L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 4); double[] aD = generateDouble(r, 4);
double[] bD = generateDouble(r, 4); double[] bD = generateDouble(r, 4);
@ -493,7 +493,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test @Test
public void testLinearCombinationDF4() { public void testLinearCombinationDF4() {
UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf4l); UniformRandomProvider r = RandomSource.create(RandomSource.WELL_1024_A, 0xdf4L);
for (int i = 0; i < 50; ++i) { for (int i = 0; i < 50; ++i) {
double[] aD = generateDouble(r, 4); double[] aD = generateDouble(r, 4);
double[] bD = generateDouble(r, 4); double[] bD = generateDouble(r, 4);
@ -537,7 +537,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
Assert.assertTrue(t1a.hashCode() != t2.hashCode()); Assert.assertTrue(t1a.hashCode() != t2.hashCode());
} }
private double[] generateDouble (final UniformRandomProvider r, int n) { private static double[] generateDouble(final UniformRandomProvider r, int n) {
double[] a = new double[n]; double[] a = new double[n];
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
a[i] = r.nextDouble(); a[i] = r.nextDouble();
@ -545,7 +545,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
return a; return a;
} }
private T[] toFieldArray (double[] a) { private T[] toFieldArray(double[] a) {
T[] f = MathArrays.buildArray(build(0).getField(), a.length); T[] f = MathArrays.buildArray(build(0).getField(), a.length);
for (int i = 0; i < a.length; ++i) { for (int i = 0; i < a.length; ++i) {
f[i] = build(a[i]); f[i] = build(a[i]);

View File

@ -1,15 +1,18 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this * contributor license agreements. See the NOTICE file distributed with
* work for additional information regarding copyright ownership. The ASF * this work for additional information regarding copyright ownership.
* licenses this file to You under the Apache License, Version 2.0 (the * The ASF licenses this file to You under the Apache License, Version 2.0
* "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with
* You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law *
* or agreed to in writing, software distributed under the License is * http://www.apache.org/licenses/LICENSE-2.0
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the specific language * Unless required by applicable law or agreed to in writing, software
* governing permissions and limitations under the License. * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.apache.commons.math4.legacy.core; package org.apache.commons.math4.legacy.core;
@ -168,7 +171,7 @@ public class IntegerSequenceTest {
Assert.assertEquals(seq.size(), r.size()); Assert.assertEquals(seq.size(), r.size());
} }
@Test(expected=MaxCountExceededException.class) @Test(expected = MaxCountExceededException.class)
public void testIncrementorCountExceeded() { public void testIncrementorCountExceeded() {
final int start = 1; final int start = 1;
final int max = 7; final int max = 7;
@ -203,7 +206,7 @@ public class IntegerSequenceTest {
Assert.assertTrue(inc.canIncrement(0)); Assert.assertTrue(inc.canIncrement(0));
} }
@Test(expected=NotStrictlyPositiveException.class) @Test(expected = NotStrictlyPositiveException.class)
public void testIncrementZeroTimes() { public void testIncrementZeroTimes() {
final int start = 1; final int start = 1;
final int max = 2; final int max = 2;
@ -245,7 +248,7 @@ public class IntegerSequenceTest {
} }
} }
@Test(expected=ZeroException.class) @Test(expected = ZeroException.class)
public void testIncrementZeroStep() { public void testIncrementZeroStep() {
final int step = 0; final int step = 0;
@ -298,7 +301,7 @@ public class IntegerSequenceTest {
} }
} }
@Test(expected=TooManyEvaluationsException.class) @Test(expected = TooManyEvaluationsException.class)
public void testIncrementorAlternateException() { public void testIncrementorAlternateException() {
final int start = 1; final int start = 1;
final int max = 2; final int max = 2;

View File

@ -1,15 +1,18 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this * contributor license agreements. See the NOTICE file distributed with
* work for additional information regarding copyright ownership. The ASF * this work for additional information regarding copyright ownership.
* licenses this file to You under the Apache License, Version 2.0 (the * The ASF licenses this file to You under the Apache License, Version 2.0
* "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with
* You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law *
* or agreed to in writing, software distributed under the License is * http://www.apache.org/licenses/LICENSE-2.0
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the specific language * Unless required by applicable law or agreed to in writing, software
* governing permissions and limitations under the License. * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.apache.commons.math4.legacy.core; package org.apache.commons.math4.legacy.core;
@ -38,12 +41,11 @@ public class MathArraysTest {
private double[] testArray = {0, 1, 2, 3, 4, 5}; private double[] testArray = {0, 1, 2, 3, 4, 5};
private double[] testWeightsArray = {0.3, 0.2, 1.3, 1.1, 1.0, 1.8}; private double[] testWeightsArray = {0.3, 0.2, 1.3, 1.1, 1.0, 1.8};
private double[] testNegativeWeightsArray = {-0.3, 0.2, -1.3, 1.1, 1.0, 1.8}; private double[] testNegativeWeightsArray = {-0.3, 0.2, -1.3, 1.1, 1.0, 1.8};
private double[] nullArray = null;
private double[] singletonArray = {0}; private double[] singletonArray = {0};
@Test @Test
public void testScale() { public void testScale() {
final double[] test = new double[] { -2.5, -1, 0, 1, 2.5 }; final double[] test = new double[] {-2.5, -1, 0, 1, 2.5};
final double[] correctTest = Arrays.copyOf(test, test.length); final double[] correctTest = Arrays.copyOf(test, test.length);
final double[] correctScaled = new double[]{5.25, 2.1, 0, -2.1, -5.25}; final double[] correctScaled = new double[]{5.25, 2.1, 0, -2.1, -5.25};
@ -62,7 +64,7 @@ public class MathArraysTest {
@Test @Test
public void testScaleInPlace() { public void testScaleInPlace() {
final double[] test = new double[] { -2.5, -1, 0, 1, 2.5 }; final double[] test = new double[] {-2.5, -1, 0, 1, 2.5};
final double[] correctScaled = new double[]{5.25, 2.1, 0, -2.1, -5.25}; final double[] correctScaled = new double[]{5.25, 2.1, 0, -2.1, -5.25};
MathArrays.scaleInPlace(-2.1, test); MathArrays.scaleInPlace(-2.1, test);
@ -72,27 +74,27 @@ public class MathArraysTest {
} }
} }
@Test(expected=DimensionMismatchException.class) @Test(expected = DimensionMismatchException.class)
public void testEbeAddPrecondition() { public void testEbeAddPrecondition() {
MathArrays.ebeAdd(new double[3], new double[4]); MathArrays.ebeAdd(new double[3], new double[4]);
} }
@Test(expected=DimensionMismatchException.class) @Test(expected = DimensionMismatchException.class)
public void testEbeSubtractPrecondition() { public void testEbeSubtractPrecondition() {
MathArrays.ebeSubtract(new double[3], new double[4]); MathArrays.ebeSubtract(new double[3], new double[4]);
} }
@Test(expected=DimensionMismatchException.class) @Test(expected = DimensionMismatchException.class)
public void testEbeMultiplyPrecondition() { public void testEbeMultiplyPrecondition() {
MathArrays.ebeMultiply(new double[3], new double[4]); MathArrays.ebeMultiply(new double[3], new double[4]);
} }
@Test(expected=DimensionMismatchException.class) @Test(expected = DimensionMismatchException.class)
public void testEbeDividePrecondition() { public void testEbeDividePrecondition() {
MathArrays.ebeDivide(new double[3], new double[4]); MathArrays.ebeDivide(new double[3], new double[4]);
} }
@Test @Test
public void testEbeAdd() { public void testEbeAdd() {
final double[] a = { 0, 1, 2 }; final double[] a = {0, 1, 2};
final double[] b = { 3, 5, 7 }; final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeAdd(a, b); final double[] r = MathArrays.ebeAdd(a, b);
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
@ -101,28 +103,30 @@ public class MathArraysTest {
} }
@Test @Test
public void testEbeSubtract() { public void testEbeSubtract() {
final double[] a = { 0, 1, 2 }; final double[] a = {0, 1, 2};
final double[] b = { 3, 5, 7 }; final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeSubtract(a, b); final double[] r = MathArrays.ebeSubtract(a, b);
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
Assert.assertEquals(a[i] - b[i], r[i], 0); Assert.assertEquals(a[i] - b[i], r[i], 0);
} }
} }
@Test @Test
public void testEbeMultiply() { public void testEbeMultiply() {
final double[] a = { 0, 1, 2 }; final double[] a = {0, 1, 2};
final double[] b = { 3, 5, 7 }; final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeMultiply(a, b); final double[] r = MathArrays.ebeMultiply(a, b);
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
Assert.assertEquals(a[i] * b[i], r[i], 0); Assert.assertEquals(a[i] * b[i], r[i], 0);
} }
} }
@Test @Test
public void testEbeDivide() { public void testEbeDivide() {
final double[] a = { 0, 1, 2 }; final double[] a = {0, 1, 2};
final double[] b = { 3, 5, 7 }; final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeDivide(a, b); final double[] r = MathArrays.ebeDivide(a, b);
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
@ -132,43 +136,43 @@ public class MathArraysTest {
@Test @Test
public void testL1DistanceDouble() { public void testL1DistanceDouble() {
double[] p1 = { 2.5, 0.0 }; double[] p1 = {2.5, 0.0};
double[] p2 = { -0.5, 4.0 }; double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(7.0, MathArrays.distance1(p1, p2), 1)); Assert.assertTrue(Precision.equals(7.0, MathArrays.distance1(p1, p2), 1));
} }
@Test @Test
public void testL1DistanceInt() { public void testL1DistanceInt() {
int[] p1 = { 3, 0 }; int[] p1 = {3, 0};
int[] p2 = { 0, 4 }; int[] p2 = {0, 4};
Assert.assertEquals(7, MathArrays.distance1(p1, p2)); Assert.assertEquals(7, MathArrays.distance1(p1, p2));
} }
@Test @Test
public void testL2DistanceDouble() { public void testL2DistanceDouble() {
double[] p1 = { 2.5, 0.0 }; double[] p1 = {2.5, 0.0};
double[] p2 = { -0.5, 4.0 }; double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(5.0, MathArrays.distance(p1, p2), 1)); Assert.assertTrue(Precision.equals(5.0, MathArrays.distance(p1, p2), 1));
} }
@Test @Test
public void testL2DistanceInt() { public void testL2DistanceInt() {
int[] p1 = { 3, 0 }; int[] p1 = {3, 0};
int[] p2 = { 0, 4 }; int[] p2 = {0, 4};
Assert.assertTrue(Precision.equals(5, MathArrays.distance(p1, p2), 1)); Assert.assertTrue(Precision.equals(5, MathArrays.distance(p1, p2), 1));
} }
@Test @Test
public void testLInfDistanceDouble() { public void testLInfDistanceDouble() {
double[] p1 = { 2.5, 0.0 }; double[] p1 = {2.5, 0.0};
double[] p2 = { -0.5, 4.0 }; double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(4.0, MathArrays.distanceInf(p1, p2), 1)); Assert.assertTrue(Precision.equals(4.0, MathArrays.distanceInf(p1, p2), 1));
} }
@Test @Test
public void testLInfDistanceInt() { public void testLInfDistanceInt() {
int[] p1 = { 3, 0 }; int[] p1 = {3, 0};
int[] p2 = { 0, 4 }; int[] p2 = {0, 4};
Assert.assertEquals(4, MathArrays.distanceInf(p1, p2)); Assert.assertEquals(4, MathArrays.distanceInf(p1, p2));
} }
@ -222,77 +226,77 @@ public class MathArraysTest {
@Test @Test
public void testIsMonotonic() { public void testIsMonotonic() {
Assert.assertFalse(MathArrays.isMonotonic(new double[] { -15, -5.5, -1, -1, 2, 15 }, Assert.assertFalse(MathArrays.isMonotonic(new double[] {-15, -5.5, -1, -1, 2, 15},
MathArrays.OrderDirection.INCREASING, true)); MathArrays.OrderDirection.INCREASING, true));
Assert.assertTrue(MathArrays.isMonotonic(new double[] { -15, -5.5, -1, 0, 2, 15 }, Assert.assertTrue(MathArrays.isMonotonic(new double[] {-15, -5.5, -1, 0, 2, 15},
MathArrays.OrderDirection.INCREASING, true)); MathArrays.OrderDirection.INCREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new double[] { -15, -5.5, -1, -2, 2 }, Assert.assertFalse(MathArrays.isMonotonic(new double[] {-15, -5.5, -1, -2, 2},
MathArrays.OrderDirection.INCREASING, false)); MathArrays.OrderDirection.INCREASING, false));
Assert.assertTrue(MathArrays.isMonotonic(new double[] { -15, -5.5, -1, -1, 2 }, Assert.assertTrue(MathArrays.isMonotonic(new double[] {-15, -5.5, -1, -1, 2},
MathArrays.OrderDirection.INCREASING, false)); MathArrays.OrderDirection.INCREASING, false));
Assert.assertFalse(MathArrays.isMonotonic(new double[] { 3, 3, -5.5, -11, -27.5 }, Assert.assertFalse(MathArrays.isMonotonic(new double[] {3, 3, -5.5, -11, -27.5},
MathArrays.OrderDirection.DECREASING, true)); MathArrays.OrderDirection.DECREASING, true));
Assert.assertTrue(MathArrays.isMonotonic(new double[] { 3, 2, -5.5, -11, -27.5 }, Assert.assertTrue(MathArrays.isMonotonic(new double[] {3, 2, -5.5, -11, -27.5},
MathArrays.OrderDirection.DECREASING, true)); MathArrays.OrderDirection.DECREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new double[] { 3, -1, 0, -5.5, -11, -27.5 }, Assert.assertFalse(MathArrays.isMonotonic(new double[] {3, -1, 0, -5.5, -11, -27.5},
MathArrays.OrderDirection.DECREASING, false)); MathArrays.OrderDirection.DECREASING, false));
Assert.assertTrue(MathArrays.isMonotonic(new double[] { 3, 0, 0, -5.5, -11, -27.5 }, Assert.assertTrue(MathArrays.isMonotonic(new double[] {3, 0, 0, -5.5, -11, -27.5},
MathArrays.OrderDirection.DECREASING, false)); MathArrays.OrderDirection.DECREASING, false));
} }
@Test @Test
public void testIsMonotonicComparable() { public void testIsMonotonicComparable() {
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(-15), Assert.assertFalse(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(-5.5),
new Double(-1),
new Double(-1),
new Double(2),
new Double(15) },
MathArrays.OrderDirection.INCREASING, true));
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(-15),
new Double(-5.5), new Double(-5.5),
new Double(-1), new Double(-1),
new Double(0), new Double(-1),
new Double(2), new Double(2),
new Double(15) }, new Double(15) },
MathArrays.OrderDirection.INCREASING, true)); MathArrays.OrderDirection.INCREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(-15), Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(-5.5), new Double(-5.5),
new Double(-1), new Double(-1),
new Double(-2), new Double(0),
new Double(2) }, new Double(2),
MathArrays.OrderDirection.INCREASING, false)); new Double(15) },
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(-15), MathArrays.OrderDirection.INCREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(-5.5), new Double(-5.5),
new Double(-1), new Double(-1),
new Double(-1), new Double(-2),
new Double(2) }, new Double(2) },
MathArrays.OrderDirection.INCREASING, false)); MathArrays.OrderDirection.INCREASING, false));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(3), Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(3), new Double(-5.5),
new Double(-5.5), new Double(-1),
new Double(-11), new Double(-1),
new Double(-27.5) }, new Double(2) },
MathArrays.OrderDirection.DECREASING, true)); MathArrays.OrderDirection.INCREASING, false));
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(3), Assert.assertFalse(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(2), new Double(3),
new Double(-5.5), new Double(-5.5),
new Double(-11), new Double(-11),
new Double(-27.5) }, new Double(-27.5) },
MathArrays.OrderDirection.DECREASING, true)); MathArrays.OrderDirection.DECREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(3), Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(-1), new Double(2),
new Double(0), new Double(-5.5),
new Double(-5.5), new Double(-11),
new Double(-11), new Double(-27.5) },
new Double(-27.5) }, MathArrays.OrderDirection.DECREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(-1),
new Double(0),
new Double(-5.5),
new Double(-11),
new Double(-27.5) },
MathArrays.OrderDirection.DECREASING, false)); MathArrays.OrderDirection.DECREASING, false));
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(3), Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(0), new Double(0),
new Double(0), new Double(0),
new Double(-5.5), new Double(-5.5),
new Double(-11), new Double(-11),
new Double(-27.5) }, new Double(-27.5) },
MathArrays.OrderDirection.DECREASING, false)); MathArrays.OrderDirection.DECREASING, false));
} }
@ -386,24 +390,24 @@ public class MathArraysTest {
@Test @Test
public void testCheckNotNaN() { public void testCheckNotNaN() {
final double[] withoutNaN = { Double.NEGATIVE_INFINITY, final double[] withoutNaN = {Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE, -Double.MAX_VALUE,
-1, 0, -1, 0,
Double.MIN_VALUE, Double.MIN_VALUE,
AccurateMath.ulp(1d), AccurateMath.ulp(1d),
1, 3, 113, 4769, 1, 3, 113, 4769,
Double.MAX_VALUE, Double.MAX_VALUE,
Double.POSITIVE_INFINITY }; Double.POSITIVE_INFINITY };
final double[] withNaN = { Double.NEGATIVE_INFINITY, final double[] withNaN = {Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE, -Double.MAX_VALUE,
-1, 0, -1, 0,
Double.MIN_VALUE, Double.MIN_VALUE,
AccurateMath.ulp(1d), AccurateMath.ulp(1d),
1, 3, 113, 4769, 1, 3, 113, 4769,
Double.MAX_VALUE, Double.MAX_VALUE,
Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY,
Double.NaN }; Double.NaN };
final double[] nullArray = null; final double[] nullArray = null;
@ -424,7 +428,7 @@ public class MathArraysTest {
} }
} }
@Test(expected=DimensionMismatchException.class) @Test(expected = DimensionMismatchException.class)
public void testCheckEqualLength1() { public void testCheckEqualLength1() {
MathArrays.checkEqualLength(new double[] {1, 2, 3}, MathArrays.checkEqualLength(new double[] {1, 2, 3},
new double[] {1, 2, 3, 4}); new double[] {1, 2, 3, 4});
@ -439,41 +443,41 @@ public class MathArraysTest {
@Test @Test
public void testArrayEquals() { public void testArrayEquals() {
Assert.assertFalse(MathArrays.equals(new double[] { 1d }, null)); Assert.assertFalse(MathArrays.equals(new double[] {1d}, null));
Assert.assertFalse(MathArrays.equals(null, new double[] { 1d })); Assert.assertFalse(MathArrays.equals(null, new double[] {1d}));
Assert.assertTrue(MathArrays.equals((double[]) null, (double[]) null)); Assert.assertTrue(MathArrays.equals((double[]) null, (double[]) null));
Assert.assertFalse(MathArrays.equals(new double[] { 1d }, new double[0])); Assert.assertFalse(MathArrays.equals(new double[] {1d}, new double[0]));
Assert.assertTrue(MathArrays.equals(new double[] { 1d }, new double[] { 1d })); Assert.assertTrue(MathArrays.equals(new double[] {1d}, new double[] {1d}));
Assert.assertTrue(MathArrays.equals(new double[] { Double.POSITIVE_INFINITY, Assert.assertTrue(MathArrays.equals(new double[] {Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d }, Double.NEGATIVE_INFINITY, 1d, 0d},
new double[] { Double.POSITIVE_INFINITY, new double[] {Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d })); Double.NEGATIVE_INFINITY, 1d, 0d}));
Assert.assertFalse(MathArrays.equals(new double[] { Double.NaN }, Assert.assertFalse(MathArrays.equals(new double[] {Double.NaN},
new double[] { Double.NaN })); new double[] {Double.NaN}));
Assert.assertFalse(MathArrays.equals(new double[] { Double.POSITIVE_INFINITY }, Assert.assertFalse(MathArrays.equals(new double[] {Double.POSITIVE_INFINITY},
new double[] { Double.NEGATIVE_INFINITY })); new double[] {Double.NEGATIVE_INFINITY}));
Assert.assertFalse(MathArrays.equals(new double[] { 1d }, Assert.assertFalse(MathArrays.equals(new double[] {1d},
new double[] { AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d) })); new double[] {AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d)}));
} }
@Test @Test
public void testArrayEqualsIncludingNaN() { public void testArrayEqualsIncludingNaN() {
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { 1d }, null)); Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {1d}, null));
Assert.assertFalse(MathArrays.equalsIncludingNaN(null, new double[] { 1d })); Assert.assertFalse(MathArrays.equalsIncludingNaN(null, new double[] {1d}));
Assert.assertTrue(MathArrays.equalsIncludingNaN((double[]) null, (double[]) null)); Assert.assertTrue(MathArrays.equalsIncludingNaN((double[]) null, (double[]) null));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { 1d }, new double[0])); Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {1d}, new double[0]));
Assert.assertTrue(MathArrays.equalsIncludingNaN(new double[] { 1d }, new double[] { 1d })); Assert.assertTrue(MathArrays.equalsIncludingNaN(new double[] {1d}, new double[] {1d}));
Assert.assertTrue(MathArrays.equalsIncludingNaN(new double[] { Double.NaN, Double.POSITIVE_INFINITY, Assert.assertTrue(MathArrays.equalsIncludingNaN(new double[] {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d }, Double.NEGATIVE_INFINITY, 1d, 0d},
new double[] { Double.NaN, Double.POSITIVE_INFINITY, new double[] {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d })); Double.NEGATIVE_INFINITY, 1d, 0d}));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { Double.POSITIVE_INFINITY }, Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {Double.POSITIVE_INFINITY},
new double[] { Double.NEGATIVE_INFINITY })); new double[] {Double.NEGATIVE_INFINITY}));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { 1d }, Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {1d},
new double[] { AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d) })); new double[] {AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d)}));
} }
@Test @Test
@ -490,7 +494,7 @@ public class MathArraysTest {
// Ignore NaNs // Ignore NaNs
double[] testValues3 = new double[] {-1, -1, Double.NaN, 1, Double.NaN}; double[] testValues3 = new double[] {-1, -1, Double.NaN, 1, Double.NaN};
Assert.assertArrayEquals(new double[] {1, 1,Double.NaN, -1, Double.NaN}, Assert.assertArrayEquals(new double[] {1, 1, Double.NaN, -1, Double.NaN},
MathArrays.normalizeArray(testValues3, 1), MathArrays.normalizeArray(testValues3, 1),
Double.MIN_VALUE); Double.MIN_VALUE);
@ -499,26 +503,26 @@ public class MathArraysTest {
try { try {
MathArrays.normalizeArray(zeroSum, 1); MathArrays.normalizeArray(zeroSum, 1);
Assert.fail("expecting MathArithmeticException"); Assert.fail("expecting MathArithmeticException");
} catch (MathArithmeticException ex) {} } catch (MathArithmeticException ex) { /* ignore */ }
// Infinite elements -> MathArithmeticException // Infinite elements -> MathArithmeticException
double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY}; double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY};
try { try {
MathArrays.normalizeArray(hasInf, 1); MathArrays.normalizeArray(hasInf, 1);
Assert.fail("expecting MathIllegalArgumentException"); Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {} } catch (MathIllegalArgumentException ex) { /* ignore */ }
// Infinite target -> MathIllegalArgumentException // Infinite target -> MathIllegalArgumentException
try { try {
MathArrays.normalizeArray(testValues1, Double.POSITIVE_INFINITY); MathArrays.normalizeArray(testValues1, Double.POSITIVE_INFINITY);
Assert.fail("expecting MathIllegalArgumentException"); Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {} } catch (MathIllegalArgumentException ex) { /* ignore */ }
// NaN target -> MathIllegalArgumentException // NaN target -> MathIllegalArgumentException
try { try {
MathArrays.normalizeArray(testValues1, Double.NaN); MathArrays.normalizeArray(testValues1, Double.NaN);
Assert.fail("expecting MathIllegalArgumentException"); Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {} } catch (MathIllegalArgumentException ex) { /* ignore */ }
} }
@Test @Test
@ -528,17 +532,17 @@ public class MathArraysTest {
* h=[1,0.8,0.5,0.3] * h=[1,0.8,0.5,0.3]
* convolve(x,h) -> array([ 1.2 , -0.84, 0.56, 0.58, 0.16, 0.42]) * convolve(x,h) -> array([ 1.2 , -0.84, 0.56, 0.58, 0.16, 0.42])
*/ */
double[] x1 = { 1.2, -1.8, 1.4 }; double[] x1 = {1.2, -1.8, 1.4};
double[] h1 = { 1, 0.8, 0.5, 0.3 }; double[] h1 = {1, 0.8, 0.5, 0.3};
double[] y1 = { 1.2, -0.84, 0.56, 0.58, 0.16, 0.42 }; double[] y1 = {1.2, -0.84, 0.56, 0.58, 0.16, 0.42};
double tolerance = 1e-13; double tolerance = 1e-13;
double[] yActual = MathArrays.convolve(x1, h1); double[] yActual = MathArrays.convolve(x1, h1);
Assert.assertArrayEquals(y1, yActual, tolerance); Assert.assertArrayEquals(y1, yActual, tolerance);
double[] x2 = { 1, 2, 3 }; double[] x2 = {1, 2, 3};
double[] h2 = { 0, 1, 0.5 }; double[] h2 = {0, 1, 0.5};
double[] y2 = { 0, 1, 2.5, 4, 1.5 }; double[] y2 = {0, 1, 2.5, 4, 1.5};
yActual = MathArrays.convolve(x2, h2); yActual = MathArrays.convolve(x2, h2);
Assert.assertArrayEquals(y2, yActual, tolerance); Assert.assertArrayEquals(y2, yActual, tolerance);
@ -628,6 +632,7 @@ public class MathArraysTest {
@Test @Test
public void testVerifyValuesNegative() { public void testVerifyValuesNegative() {
final double[] nullArray = null;
Assert.assertFalse(MathArrays.verifyValues(singletonArray, 0, 0)); Assert.assertFalse(MathArrays.verifyValues(singletonArray, 0, 0));
Assert.assertFalse(MathArrays.verifyValues(testArray, 0, 0)); Assert.assertFalse(MathArrays.verifyValues(testArray, 0, 0));
try { try {
@ -706,7 +711,7 @@ public class MathArraysTest {
Assert.assertEquals(0, MathArrays.concatenate(z, z, z).length); Assert.assertEquals(0, MathArrays.concatenate(z, z, z).length);
} }
@Test(expected=NullPointerException.class) @Test(expected = NullPointerException.class)
public void testConcatenateNullArguments() { public void testConcatenateNullArguments() {
final double[] x = new double[] {0, 1, 2}; final double[] x = new double[] {0, 1, 2};
MathArrays.concatenate(x, null); MathArrays.concatenate(x, null);
@ -721,10 +726,10 @@ public class MathArraysTest {
@Test @Test
public void testUniqueInfiniteValues() { public void testUniqueInfiniteValues() {
final double [] x = {0, Double.NEGATIVE_INFINITY, 3, Double.NEGATIVE_INFINITY, final double[] x = {0, Double.NEGATIVE_INFINITY, 3, Double.NEGATIVE_INFINITY,
3, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}; 3, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY};
final double[] u = {Double.POSITIVE_INFINITY, 3, 0, Double.NEGATIVE_INFINITY}; final double[] u = {Double.POSITIVE_INFINITY, 3, 0, Double.NEGATIVE_INFINITY};
Assert.assertArrayEquals(u , MathArrays.unique(x), 0); Assert.assertArrayEquals(u, MathArrays.unique(x), 0);
} }
@Test @Test
@ -740,7 +745,7 @@ public class MathArraysTest {
Assert.assertEquals(Double.NEGATIVE_INFINITY, u[4], 0); Assert.assertEquals(Double.NEGATIVE_INFINITY, u[4], 0);
} }
@Test(expected=NullPointerException.class) @Test(expected = NullPointerException.class)
public void testUniqueNullArgument() { public void testUniqueNullArgument() {
MathArrays.unique(null); MathArrays.unique(null);
} }

View File

@ -1,15 +1,18 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this * contributor license agreements. See the NOTICE file distributed with
* work for additional information regarding copyright ownership. The ASF * this work for additional information regarding copyright ownership.
* licenses this file to You under the Apache License, Version 2.0 (the * The ASF licenses this file to You under the Apache License, Version 2.0
* "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with
* You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law *
* or agreed to in writing, software distributed under the License is * http://www.apache.org/licenses/LICENSE-2.0
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the specific language * Unless required by applicable law or agreed to in writing, software
* governing permissions and limitations under the License. * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.apache.commons.math4.legacy.core; package org.apache.commons.math4.legacy.core;
@ -93,12 +96,12 @@ public class PairTest {
private static class MyInteger { private static class MyInteger {
private int i; private int i;
public MyInteger(int i) { MyInteger(int i) {
this.i = i; this.i = i;
} }
public void set(int i) { public void set(int value) {
this.i = i; this.i = value;
} }
@Override @Override

View File

@ -50,24 +50,26 @@ public class DfpDecTest {
private void test(Dfp x, Dfp y, int flags, String desc) { private void test(Dfp x, Dfp y, int flags, String desc) {
boolean b = x.equals(y); boolean b = x.equals(y);
if (!x.equals(y) && !x.unequal(y)) // NaNs involved if (!x.equals(y) && !x.unequal(y)) { // NaNs involved
b = (x.toString().equals(y.toString())); b = x.toString().equals(y.toString());
}
if (x.equals(new DfpDec(field, 0))) // distinguish +/- zero if (x.equals(new DfpDec(field, 0))) { // distinguish +/- zero
b = (b && (x.toString().equals(y.toString()))); b = b && (x.toString().equals(y.toString()));
}
b = (b && x.getField().getIEEEFlags() == flags); b = b && x.getField().getIEEEFlags() == flags;
if (!b) { if (!b) {
Assert.assertTrue("assertion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); Assert.assertTrue(
"assertion failed " + desc + " x = " + x.toString() + " flags = " + x.getField().getIEEEFlags(), b);
} }
x.getField().clearIEEEFlags(); x.getField().clearIEEEFlags();
} }
@Test @Test
public void testRound() public void testRound() {
{
field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN);
test(new DfpDec(field, "12345678901234567890"), test(new DfpDec(field, "12345678901234567890"),
@ -283,8 +285,7 @@ public class DfpDecTest {
} }
@Test @Test
public void testRoundDecimal10() public void testRoundDecimal10() {
{
field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN);
test(new Decimal10(field, "1234567891234567890"), test(new Decimal10(field, "1234567891234567890"),
@ -390,7 +391,7 @@ public class DfpDecTest {
// RoundDecimal10 up // RoundDecimal10 up
test(new Decimal10(field, 1234567890).add(new Decimal10(field, "0.1")), test(new Decimal10(field, 1234567890).add(new Decimal10(field, "0.1")),
new Decimal10(field, 1234567891l), new Decimal10(field, 1234567891L),
DfpField.FLAG_INEXACT, "RoundDecimal10 #25"); DfpField.FLAG_INEXACT, "RoundDecimal10 #25");
test(new Decimal10(field, "1234567890").add(new Decimal10(field, "0.0001")), test(new Decimal10(field, "1234567890").add(new Decimal10(field, "0.0001")),
@ -500,8 +501,7 @@ public class DfpDecTest {
} }
@Test @Test
public void testNextAfter() public void testNextAfter() {
{
test(new DfpDec(field, 1).nextAfter(pinf), test(new DfpDec(field, 1).nextAfter(pinf),
new DfpDec(field, "1.0000000000000001"), new DfpDec(field, "1.0000000000000001"),
0, "NextAfter #1"); 0, "NextAfter #1");
@ -531,7 +531,7 @@ public class DfpDecTest {
0, "NextAfter #6"); 0, "NextAfter #6");
test(new DfpDec(field, (byte) 2).nextAfter(new DfpDec(field, 2)), test(new DfpDec(field, (byte) 2).nextAfter(new DfpDec(field, 2)),
new DfpDec(field, 2l), new DfpDec(field, 2L),
0, "NextAfter #7"); 0, "NextAfter #7");
test(new DfpDec(field, 0).nextAfter(new DfpDec(field, 0)), test(new DfpDec(field, 0).nextAfter(new DfpDec(field, 0)),
@ -552,15 +552,15 @@ public class DfpDecTest {
test(new DfpDec(field, "-1e-131092").nextAfter(pinf), test(new DfpDec(field, "-1e-131092").nextAfter(pinf),
new DfpDec(field, "-0"), new DfpDec(field, "-0"),
DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #12"); DfpField.FLAG_UNDERFLOW | DfpField.FLAG_INEXACT, "Next After #12");
test(new DfpDec(field, "1e-131092").nextAfter(ninf), test(new DfpDec(field, "1e-131092").nextAfter(ninf),
new DfpDec(field, "0"), new DfpDec(field, "0"),
DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #13"); DfpField.FLAG_UNDERFLOW | DfpField.FLAG_INEXACT, "Next After #13");
test(new DfpDec(field, "9.9999999999999999e131078").nextAfter(pinf), test(new DfpDec(field, "9.9999999999999999e131078").nextAfter(pinf),
pinf, pinf,
DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14"); DfpField.FLAG_OVERFLOW | DfpField.FLAG_INEXACT, "Next After #14");
} }
} }

View File

@ -56,29 +56,30 @@ public class DfpMathTest {
// Generic test function. Takes params x and y and tests them for // Generic test function. Takes params x and y and tests them for
// equality. Then checks the status flags against the flags argument. // equality. Then checks the status flags against the flags argument.
// If the test fail, it prints the desc string // If the test fail, it prints the desc string
private void test(Dfp x, Dfp y, int flags, String desc) private void test(Dfp x, Dfp y, int flags, String desc) {
{
boolean b = x.equals(y); boolean b = x.equals(y);
if (!x.equals(y) && !x.unequal(y)) // NaNs involved if (!x.equals(y) && !x.unequal(y)) { // NaNs involved
b = (x.toString().equals(y.toString())); b = x.toString().equals(y.toString());
}
if (x.equals(factory.newDfp("0"))) // distinguish +/- zero if (x.equals(factory.newDfp("0"))) { // distinguish +/- zero
b = (b && (x.toString().equals(y.toString()))); b = b && (x.toString().equals(y.toString()));
}
b = (b && x.getField().getIEEEFlags() == flags); b = b && x.getField().getIEEEFlags() == flags;
if (!b) { if (!b) {
Assert.assertTrue("assertion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); Assert.assertTrue(
"assertion failed " + desc + " x = " + x.toString() + " flags = " + x.getField().getIEEEFlags(), b);
} }
x.getField().clearIEEEFlags(); x.getField().clearIEEEFlags();
} }
@Test @Test
public void testPow() public void testPow() {
{ // Test special cases exponent of zero
// Test special cases exponent of zero
test(DfpMath.pow(factory.newDfp("0"), factory.newDfp("0")), test(DfpMath.pow(factory.newDfp("0"), factory.newDfp("0")),
factory.newDfp("1"), factory.newDfp("1"),
0, "pow #1"); 0, "pow #1");
@ -464,24 +465,23 @@ public class DfpMathTest {
test(DfpMath.pow(factory.newDfp("-2"), factory.newDfp("-4.1")), test(DfpMath.pow(factory.newDfp("-2"), factory.newDfp("-4.1")),
qnan, qnan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "pow #87"); DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "pow #87");
// Some fractional cases. // Some fractional cases.
test(DfpMath.pow(factory.newDfp("2"),factory.newDfp("1.5")), test(DfpMath.pow(factory.newDfp("2"), factory.newDfp("1.5")),
factory.newDfp("2.8284271247461901"), factory.newDfp("2.8284271247461901"),
DfpField.FLAG_INEXACT, "pow #88"); DfpField.FLAG_INEXACT, "pow #88");
} }
@Test @Test
public void testSin() public void testSin() {
{
test(DfpMath.sin(pinf), test(DfpMath.sin(pinf),
nan, nan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "sin #1"); DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "sin #1");
test(DfpMath.sin(nan), test(DfpMath.sin(nan),
nan, nan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "sin #2"); DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "sin #2");
test(DfpMath.sin(factory.getZero()), test(DfpMath.sin(factory.getZero()),
factory.getZero(), factory.getZero(),

View File

@ -27,11 +27,6 @@ import org.junit.Test;
public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> { public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Override
protected Dfp build(final double x) {
return field.newDfp(x);
}
private DfpField field; private DfpField field;
private Dfp pinf; private Dfp pinf;
private Dfp ninf; private Dfp ninf;
@ -39,6 +34,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
private Dfp snan; private Dfp snan;
private Dfp qnan; private Dfp qnan;
@Override
protected Dfp build(final double x) {
return field.newDfp(x);
}
@Before @Before
public void setUp() { public void setUp() {
// Some basic setup. Define some constants and clear the status flags // Some basic setup. Define some constants and clear the status flags
@ -67,16 +67,20 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
private void test(Dfp x, Dfp y, int flags, String desc) { private void test(Dfp x, Dfp y, int flags, String desc) {
boolean b = x.equals(y); boolean b = x.equals(y);
if (!x.equals(y) && !x.unequal(y)) // NaNs involved if (!x.equals(y) && !x.unequal(y)) { // NaNs involved
b = (x.toString().equals(y.toString())); b = x.toString().equals(y.toString());
}
if (x.equals(field.newDfp("0"))) // distinguish +/- zero if (x.equals(field.newDfp("0"))) { // distinguish +/- zero
b = (b && (x.toString().equals(y.toString()))); b = b && (x.toString().equals(y.toString()));
}
b = (b && x.getField().getIEEEFlags() == flags); b = b && x.getField().getIEEEFlags() == flags;
if (!b) if (!b) {
Assert.assertTrue("assertion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); Assert.assertTrue(
"assertion failed " + desc + " x = " + x.toString() + " flags = " + x.getField().getIEEEFlags(), b);
}
x.getField().clearIEEEFlags(); x.getField().clearIEEEFlags();
} }
@ -103,11 +107,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Test @Test
public void testLongConstructor() { public void testLongConstructor() {
Assert.assertEquals("0.", new Dfp(field, 0l).toString()); Assert.assertEquals("0.", new Dfp(field, 0L).toString());
Assert.assertEquals("1.", new Dfp(field, 1l).toString()); Assert.assertEquals("1.", new Dfp(field, 1L).toString());
Assert.assertEquals("-1.", new Dfp(field, -1l).toString()); Assert.assertEquals("-1.", new Dfp(field, -1L).toString());
Assert.assertEquals("1234567890.", new Dfp(field, 1234567890l).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890L).toString());
Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890l).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890L).toString());
Assert.assertEquals("-9223372036854775808.", new Dfp(field, Long.MIN_VALUE).toString()); Assert.assertEquals("-9223372036854775808.", new Dfp(field, Long.MIN_VALUE).toString());
Assert.assertEquals("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString()); Assert.assertEquals("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString());
} }
@ -370,25 +374,25 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
// utility function to help test comparisons // utility function to help test comparisons
private void cmptst(Dfp a, Dfp b, String op, boolean result, double num) { private void cmptst(Dfp a, Dfp b, String op, boolean result, double num) {
if (op == "equal") { if (op.equals("equal")) {
if (a.equals(b) != result) { if (a.equals(b) != result) {
assertionFailOpNum(op, num); assertionFailOpNum(op, num);
} }
} }
if (op == "unequal") { if (op.equals("unequal")) {
if (a.unequal(b) != result) { if (a.unequal(b) != result) {
assertionFailOpNum(op, num); assertionFailOpNum(op, num);
} }
} }
if (op == "lessThan") { if (op.equals("lessThan")) {
if (a.lessThan(b) != result) { if (a.lessThan(b) != result) {
assertionFailOpNum(op, num); assertionFailOpNum(op, num);
} }
} }
if (op == "greaterThan") { if (op.equals("greaterThan")) {
if (a.greaterThan(b) != result) { if (a.greaterThan(b) != result) {
assertionFailOpNum(op, num); assertionFailOpNum(op, num);
} }
@ -580,7 +584,7 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
cmptst(qnan.negate(), qnan, "unequal", false, 52); cmptst(qnan.negate(), qnan, "unequal", false, 52);
if (field.getIEEEFlags() != 0) { if (field.getIEEEFlags() != 0) {
assertionFail("compare unequal flags = "+field.getIEEEFlags()); assertionFail("compare unequal flags = " + field.getIEEEFlags());
} }
// //
@ -674,7 +678,7 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
//lessThan compares with nans should raise FLAG_INVALID //lessThan compares with nans should raise FLAG_INVALID
if (field.getIEEEFlags() != DfpField.FLAG_INVALID) { if (field.getIEEEFlags() != DfpField.FLAG_INVALID) {
assertionFail("compare lessThan flags = "+field.getIEEEFlags()); assertionFail("compare lessThan flags = " + field.getIEEEFlags());
} }
field.clearIEEEFlags(); field.clearIEEEFlags();
@ -767,9 +771,9 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
cmptst(snan.negate(), snan, "greaterThan", false, 51); cmptst(snan.negate(), snan, "greaterThan", false, 51);
cmptst(qnan.negate(), qnan, "greaterThan", false, 52); cmptst(qnan.negate(), qnan, "greaterThan", false, 52);
//greaterThan compares with nans should raise FLAG_INVALID // greaterThan compares with nans should raise FLAG_INVALID
if (field.getIEEEFlags() != DfpField.FLAG_INVALID) { if (field.getIEEEFlags() != DfpField.FLAG_INVALID) {
assertionFail("compare greaterThan flags = "+field.getIEEEFlags()); assertionFail("compare greaterThan flags = " + field.getIEEEFlags());
} }
field.clearIEEEFlags(); field.clearIEEEFlags();
} }
@ -1220,15 +1224,15 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
test(field.newDfp("-1e-131092").nextAfter(pinf), test(field.newDfp("-1e-131092").nextAfter(pinf),
field.newDfp("-0"), field.newDfp("-0"),
DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #12"); DfpField.FLAG_UNDERFLOW | DfpField.FLAG_INEXACT, "Next After #12");
test(field.newDfp("1e-131092").nextAfter(ninf), test(field.newDfp("1e-131092").nextAfter(ninf),
field.newDfp("0"), field.newDfp("0"),
DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #13"); DfpField.FLAG_UNDERFLOW | DfpField.FLAG_INEXACT, "Next After #13");
test(field.newDfp("9.9999999999999999999e131078").nextAfter(pinf), test(field.newDfp("9.9999999999999999999e131078").nextAfter(pinf),
pinf, pinf,
DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14"); DfpField.FLAG_OVERFLOW | DfpField.FLAG_INEXACT, "Next After #14");
} }
@Test @Test
@ -1563,11 +1567,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Test @Test
public void testIssue567() { public void testIssue567() {
DfpField field = new DfpField(100); DfpField localField = new DfpField(100);
Assert.assertEquals(0.0, field.getZero().toDouble(), Precision.SAFE_MIN); Assert.assertEquals(0.0, localField.getZero().toDouble(), Precision.SAFE_MIN);
Assert.assertEquals(0.0, field.newDfp(0.0).toDouble(), Precision.SAFE_MIN); Assert.assertEquals(0.0, localField.newDfp(0.0).toDouble(), Precision.SAFE_MIN);
Assert.assertEquals(-1, AccurateMath.copySign(1, field.newDfp(-0.0).toDouble()), Precision.EPSILON); Assert.assertEquals(-1, AccurateMath.copySign(1, localField.newDfp(-0.0).toDouble()), Precision.EPSILON);
Assert.assertEquals(+1, AccurateMath.copySign(1, field.newDfp(+0.0).toDouble()), Precision.EPSILON); Assert.assertEquals(+1, AccurateMath.copySign(1, localField.newDfp(+0.0).toDouble()), Precision.EPSILON);
} }
@Test @Test
@ -1660,15 +1664,15 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
Assert.assertTrue(var5.equals(var6) ? var5.hashCode() == var6.hashCode() : true); Assert.assertTrue(var5.equals(var6) ? var5.hashCode() == var6.hashCode() : true);
} }
private static void assertionFail(String content){ private static void assertionFail(String content) {
Assert.fail("assertion failed: " + content); Assert.fail("assertion failed: " + content);
} }
private static void assertionFailOpNum(String op, double num){ private static void assertionFailOpNum(String op, double num) {
assertionFail(op + " compare #" + num); assertionFail(op + " compare #" + num);
} }
private static final void assertionFailDfpField(DfpField field){ private static void assertionFailDfpField(DfpField field) {
assertionFail("compare flags = " + field.getIEEEFlags()); assertionFail("compare flags = " + field.getIEEEFlags());
} }
} }

View File

@ -56,7 +56,7 @@ public class AccurateMathStrictComparisonTest {
-Double.MIN_VALUE, Double.MIN_VALUE, // 12,13 -Double.MIN_VALUE, Double.MIN_VALUE, // 12,13
}; };
private static final Float [] FLOAT_SPECIAL_VALUES = { private static final Float[] FLOAT_SPECIAL_VALUES = {
-0.0f, +0.0f, // 1,2 -0.0f, +0.0f, // 1,2
Float.NaN, // 3 Float.NaN, // 3
Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, // 4,5 Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, // 4,5
@ -64,13 +64,13 @@ public class AccurateMathStrictComparisonTest {
-Float.MIN_VALUE, -Float.MAX_VALUE, // 8,9 -Float.MIN_VALUE, -Float.MAX_VALUE, // 8,9
}; };
private static final Object [] LONG_SPECIAL_VALUES = { private static final Object[] LONG_SPECIAL_VALUES = {
-1,0,1, // 1,2,3 -1, 0, 1, // 1,2,3
Long.MIN_VALUE, Long.MAX_VALUE, // 4,5 Long.MIN_VALUE, Long.MAX_VALUE, // 4,5
}; };
private static final Object[] INT_SPECIAL_VALUES = { private static final Object[] INT_SPECIAL_VALUES = {
-1,0,1, // 1,2,3 -1, 0, 1, // 1,2,3
Integer.MIN_VALUE, Integer.MAX_VALUE, // 4,5 Integer.MIN_VALUE, Integer.MAX_VALUE, // 4,5
}; };
@ -79,17 +79,18 @@ public class AccurateMathStrictComparisonTest {
private final Type[] types; private final Type[] types;
private final Object[][] valueArrays; private final Object[][] valueArrays;
public AccurateMathStrictComparisonTest(Method m, Method f, Type[] types, Object[][] data) throws Exception{ public AccurateMathStrictComparisonTest(Method m, Method f, Type[] types, Object[][] data) throws Exception {
this.mathMethod=m; this.mathMethod = m;
this.fastMethod=f; this.fastMethod = f;
this.types=types; this.types = types;
this.valueArrays=data; this.valueArrays = data;
} }
@Test @Test
public void test1() throws Exception{ public void test1() throws Exception {
setupMethodCall(mathMethod, fastMethod, types, valueArrays); setupMethodCall(mathMethod, fastMethod, types, valueArrays);
} }
private static boolean isNumber(Double d) { private static boolean isNumber(Double d) {
return !(d.isInfinite() || d.isNaN()); return !(d.isInfinite() || d.isNaN());
} }
@ -98,18 +99,18 @@ public class AccurateMathStrictComparisonTest {
return !(f.isInfinite() || f.isNaN()); return !(f.isInfinite() || f.isNaN());
} }
private static void reportFailedResults(Method mathMethod, Object[] params, Object expected, Object actual, int[] entries){ private static void reportFailedResults(Method mathMethod, Object[] params, Object expected, Object actual, int[] entries) {
final String methodName = mathMethod.getName(); final String methodName = mathMethod.getName();
String format = null; String format = null;
long actL=0; long actL = 0;
long expL=0; long expL = 0;
if (expected instanceof Double) { if (expected instanceof Double) {
Double exp = (Double) expected; Double exp = (Double) expected;
Double act = (Double) actual; Double act = (Double) actual;
if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex
actL = Double.doubleToLongBits(act); actL = Double.doubleToLongBits(act);
expL = Double.doubleToLongBits(exp); expL = Double.doubleToLongBits(exp);
if (Math.abs(actL-expL)==1) { if (Math.abs(actL - expL) == 1) {
// Not 100% sure off-by-one errors are allowed everywhere, so only allow for these methods // Not 100% sure off-by-one errors are allowed everywhere, so only allow for these methods
if (methodName.equals("toRadians") || methodName.equals("atan2")) { if (methodName.equals("toRadians") || methodName.equals("atan2")) {
return; return;
@ -117,7 +118,7 @@ public class AccurateMathStrictComparisonTest {
} }
format = "%016x"; format = "%016x";
} }
} else if (expected instanceof Float ){ } else if (expected instanceof Float) {
Float exp = (Float) expected; Float exp = (Float) expected;
Float act = (Float) actual; Float act = (Float) actual;
if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex if (isNumber(exp) && isNumber(act) && exp != 0) { // show difference as hex
@ -132,19 +133,19 @@ public class AccurateMathStrictComparisonTest {
sb.append(methodName); sb.append(methodName);
sb.append("("); sb.append("(");
String sep = ""; String sep = "";
for(Object o : params){ for (Object o : params) {
sb.append(sep); sb.append(sep);
sb.append(o); sb.append(o);
sep=", "; sep = ", ";
} }
sb.append(") expected "); sb.append(") expected ");
if (format != null){ if (format != null) {
sb.append(String.format(format, expL)); sb.append(String.format(format, expL));
} else { } else {
sb.append(expected); sb.append(expected);
} }
sb.append(" actual "); sb.append(" actual ");
if (format != null){ if (format != null) {
sb.append(String.format(format, actL)); sb.append(String.format(format, actL));
} else { } else {
sb.append(actual); sb.append(actual);
@ -156,7 +157,9 @@ public class AccurateMathStrictComparisonTest {
if (fatal) { if (fatal) {
Assert.fail(message); Assert.fail(message);
} else { } else {
// CHECKSTYLE: stop Regexp
System.out.println(message); System.out.println(message);
// CHECKSTYLE: resume Regexp
} }
} }
@ -181,7 +184,7 @@ public class AccurateMathStrictComparisonTest {
reportFailedResults(mathMethod, params, expected, actual, entries); reportFailedResults(mathMethod, params, expected, actual, entries);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
Assert.fail(mathMethod+" "+e); Assert.fail(mathMethod + " " + e);
} }
} }
@ -190,13 +193,13 @@ public class AccurateMathStrictComparisonTest {
Object[] params = new Object[types.length]; Object[] params = new Object[types.length];
int entry1 = 0; int entry1 = 0;
int[] entries = new int[types.length]; int[] entries = new int[types.length];
for(Object d : valueArrays[0]) { for (Object d : valueArrays[0]) {
entry1++; entry1++;
params[0] = d; params[0] = d;
entries[0] = entry1; entries[0] = entry1;
if (params.length > 1){ if (params.length > 1) {
int entry2 = 0; int entry2 = 0;
for(Object d1 : valueArrays[1]) { for (Object d1 : valueArrays[1]) {
entry2++; entry2++;
params[1] = d1; params[1] = d1;
entries[1] = entry2; entries[1] = entry2;
@ -210,13 +213,14 @@ public class AccurateMathStrictComparisonTest {
@Parameters @Parameters
public static List<Object[]> data() throws Exception { public static List<Object[]> data() throws Exception {
// CHECKSTYLE: stop Regexp
String singleMethod = System.getProperty("testMethod"); String singleMethod = System.getProperty("testMethod");
List<Object[]> list = new ArrayList<>(); List<Object[]> list = new ArrayList<>();
for(Method mathMethod : StrictMath.class.getDeclaredMethods()) { for (Method mathMethod : StrictMath.class.getDeclaredMethods()) {
method: method:
if (Modifier.isPublic(mathMethod.getModifiers())){// Only test public methods if (Modifier.isPublic(mathMethod.getModifiers())) { // Only test public methods
Type []types = mathMethod.getGenericParameterTypes(); Type[] types = mathMethod.getGenericParameterTypes();
if (types.length >=1) { // Only check methods with at least one parameter if (types.length >= 1) { // Only check methods with at least one parameter
try { try {
// Get the corresponding AccurateMath method // Get the corresponding AccurateMath method
Method fastMethod = AccurateMath.class.getDeclaredMethod(mathMethod.getName(), (Class[]) types); Method fastMethod = AccurateMath.class.getDeclaredMethod(mathMethod.getName(), (Class[]) types);
@ -224,24 +228,24 @@ public class AccurateMathStrictComparisonTest {
if (singleMethod != null && !fastMethod.getName().equals(singleMethod)) { if (singleMethod != null && !fastMethod.getName().equals(singleMethod)) {
break method; break method;
} }
Object [][] values = new Object[types.length][]; Object[][] values = new Object[types.length][];
int index = 0; int index = 0;
for(Type t : types) { for (Type t : types) {
if (t.equals(double.class)){ if (t.equals(double.class)) {
values[index]=DOUBLE_SPECIAL_VALUES; values[index] = DOUBLE_SPECIAL_VALUES;
} else if (t.equals(float.class)) { } else if (t.equals(float.class)) {
values[index]=FLOAT_SPECIAL_VALUES; values[index] = FLOAT_SPECIAL_VALUES;
} else if (t.equals(long.class)) { } else if (t.equals(long.class)) {
values[index]=LONG_SPECIAL_VALUES; values[index] = LONG_SPECIAL_VALUES;
} else if (t.equals(int.class)) { } else if (t.equals(int.class)) {
values[index]=INT_SPECIAL_VALUES; values[index] = INT_SPECIAL_VALUES;
} else { } else {
System.out.println("Cannot handle class "+t+" for "+mathMethod); System.out.println("Cannot handle class " + t + " for " + mathMethod);
break method; break method;
} }
index++; index++;
} }
// System.out.println(fastMethod); // System.out.println(fastMethod);
/* /*
* The current implementation runs each method as a separate test. * The current implementation runs each method as a separate test.
* Could be amended to run each value as a separate test * Could be amended to run each value as a separate test
@ -249,14 +253,16 @@ public class AccurateMathStrictComparisonTest {
list.add(new Object[]{mathMethod, fastMethod, types, values}); list.add(new Object[]{mathMethod, fastMethod, types, values});
// setupMethodCall(mathMethod, fastMethod, params, data); // setupMethodCall(mathMethod, fastMethod, params, data);
} else { } else {
System.out.println("Cannot find public AccurateMath method corresponding to: "+mathMethod); System.out
.println("Cannot find public AccurateMath method corresponding to: " + mathMethod);
} }
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
System.out.println("Cannot find AccurateMath method corresponding to: "+mathMethod); System.out.println("Cannot find AccurateMath method corresponding to: " + mathMethod);
} }
} }
} }
} }
return list; return list;
// CHECKSTYLE: resume Regexp
} }
} }

View File

@ -42,6 +42,8 @@ import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource; import org.apache.commons.rng.simple.RandomSource;
public class AccurateMathTest { public class AccurateMathTest {
// CHECKSTYLE: stop Regexp
// The above comment allowa System.out.print
private static final double MAX_ERROR_ULP = 0.51; private static final double MAX_ERROR_ULP = 0.51;
private static final int NUMBER_OF_TRIALS = 1000; private static final int NUMBER_OF_TRIALS = 1000;
@ -52,22 +54,22 @@ public class AccurateMathTest {
@Before @Before
public void setUp() { public void setUp() {
field = new DfpField(40); field = new DfpField(40);
generator = RandomSource.create(RandomSource.MT, 6176597458463500194l); generator = RandomSource.create(RandomSource.MT, 6176597458463500194L);
} }
@Test @Test
public void testMinMaxDouble() { public void testMinMaxDouble() {
double[][] pairs = { double[][] pairs = {
{ -50.0, 50.0 }, {-50.0, 50.0},
{ Double.POSITIVE_INFINITY, 1.0 }, {Double.POSITIVE_INFINITY, 1.0},
{ Double.NEGATIVE_INFINITY, 1.0 }, {Double.NEGATIVE_INFINITY, 1.0},
{ Double.NaN, 1.0 }, {Double.NaN, 1.0},
{ Double.POSITIVE_INFINITY, 0.0 }, {Double.POSITIVE_INFINITY, 0.0},
{ Double.NEGATIVE_INFINITY, 0.0 }, {Double.NEGATIVE_INFINITY, 0.0},
{ Double.NaN, 0.0 }, {Double.NaN, 0.0},
{ Double.NaN, Double.NEGATIVE_INFINITY }, {Double.NaN, Double.NEGATIVE_INFINITY},
{ Double.NaN, Double.POSITIVE_INFINITY }, {Double.NaN, Double.POSITIVE_INFINITY},
{ Precision.SAFE_MIN, Precision.EPSILON } {Precision.SAFE_MIN, Precision.EPSILON}
}; };
for (double[] pair : pairs) { for (double[] pair : pairs) {
assertEquals("min(" + pair[0] + ", " + pair[1] + ")", assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
@ -92,15 +94,15 @@ public class AccurateMathTest {
@Test @Test
public void testMinMaxFloat() { public void testMinMaxFloat() {
float[][] pairs = { float[][] pairs = {
{ -50.0f, 50.0f }, {-50.0f, 50.0f},
{ Float.POSITIVE_INFINITY, 1.0f }, {Float.POSITIVE_INFINITY, 1.0f},
{ Float.NEGATIVE_INFINITY, 1.0f }, {Float.NEGATIVE_INFINITY, 1.0f},
{ Float.NaN, 1.0f }, {Float.NaN, 1.0f},
{ Float.POSITIVE_INFINITY, 0.0f }, {Float.POSITIVE_INFINITY, 0.0f},
{ Float.NEGATIVE_INFINITY, 0.0f }, {Float.NEGATIVE_INFINITY, 0.0f},
{ Float.NaN, 0.0f }, {Float.NaN, 0.0f},
{ Float.NaN, Float.NEGATIVE_INFINITY }, {Float.NaN, Float.NEGATIVE_INFINITY},
{ Float.NaN, Float.POSITIVE_INFINITY } {Float.NaN, Float.POSITIVE_INFINITY}
}; };
for (float[] pair : pairs) { for (float[] pair : pairs) {
assertEquals("min(" + pair[0] + ", " + pair[1] + ")", assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
@ -413,21 +415,20 @@ public class AccurateMathTest {
assertEquals("pow(0.0, 0.0) should be 1.0", 1.0, AccurateMath.pow(0.0, 0.0), EXACT); assertEquals("pow(0.0, 0.0) should be 1.0", 1.0, AccurateMath.pow(0.0, 0.0), EXACT);
} }
@Test(timeout=20000L) @Test(timeout = 20000L)
public void testPowAllSpecialCases() { public void testPowAllSpecialCases() {
final double EXACT = -1.0; final double EXACT = -1.0;
final double DOUBLES[] = new double[] final double[] DOUBLES = new double[] {
{ Double.NEGATIVE_INFINITY, -0.0, Double.NaN, 0.0, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, -0.0, Double.NaN, 0.0, Double.POSITIVE_INFINITY, Long.MIN_VALUE, Integer.MIN_VALUE, Short.MIN_VALUE, Byte.MIN_VALUE,
Long.MIN_VALUE, Integer.MIN_VALUE, Short.MIN_VALUE, Byte.MIN_VALUE, -(double)Long.MIN_VALUE, -(double)Integer.MIN_VALUE, -(double)Short.MIN_VALUE, -(double)Byte.MIN_VALUE,
-(double)Long.MIN_VALUE, -(double)Integer.MIN_VALUE, -(double)Short.MIN_VALUE, -(double)Byte.MIN_VALUE, Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE,
Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE, -Byte.MAX_VALUE, -Short.MAX_VALUE, -Integer.MAX_VALUE, -Long.MAX_VALUE,
-Byte.MAX_VALUE, -Short.MAX_VALUE, -Integer.MAX_VALUE, -Long.MAX_VALUE, Float.MAX_VALUE, Double.MAX_VALUE, Double.MIN_VALUE, Float.MIN_VALUE,
Float.MAX_VALUE, Double.MAX_VALUE, Double.MIN_VALUE, Float.MIN_VALUE, -Float.MAX_VALUE, -Double.MAX_VALUE, -Double.MIN_VALUE, -Float.MIN_VALUE,
-Float.MAX_VALUE, -Double.MAX_VALUE, -Double.MIN_VALUE, -Float.MIN_VALUE, 0.5, 0.1, 0.2, 0.8, 1.1, 1.2, 1.5, 1.8, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.3, 2.2, 2.5, 2.8, 33.0, 33.1, 33.5, 33.8, 10.0, 300.0, 400.0, 500.0,
0.5, 0.1, 0.2, 0.8, 1.1, 1.2, 1.5, 1.8, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.3, 2.2, 2.5, 2.8, 33.0, 33.1, 33.5, 33.8, 10.0, 300.0, 400.0, 500.0, -0.5, -0.1, -0.2, -0.8, -1.1, -1.2, -1.5, -1.8, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -1.3, -2.2, -2.5, -2.8, -33.0, -33.1, -33.5, -33.8, -10.0, -300.0, -400.0, -500.0
-0.5, -0.1, -0.2, -0.8, -1.1, -1.2, -1.5, -1.8, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -1.3, -2.2, -2.5, -2.8, -33.0, -33.1, -33.5, -33.8, -10.0, -300.0, -400.0, -500.0 };
};
// Special cases from Math.pow javadoc: // Special cases from Math.pow javadoc:
// If the second argument is positive or negative zero, then the result is 1.0. // If the second argument is positive or negative zero, then the result is 1.0.
@ -558,11 +559,15 @@ public class AccurateMathTest {
for (double i : DOUBLES) { for (double i : DOUBLES) {
if (Math.abs(i) <= Double.MAX_VALUE) { if (Math.abs(i) <= Double.MAX_VALUE) {
// if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument // if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument
if (i % 2.0 == 0.0) assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT); if (i % 2.0 == 0.0) {
// if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
else if (Math.abs(i) % 2.0 == 1.0) assertEquals(-AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT); } else if (Math.abs(i) % 2.0 == 1.0) {
// if the second argument is finite and not an integer, then the result is NaN. // if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument
else assertEquals(Double.NaN, AccurateMath.pow(d, i), EXACT); assertEquals(-AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
} else {
// if the second argument is finite and not an integer, then the result is NaN.
assertEquals(Double.NaN, AccurateMath.pow(d, i), EXACT);
}
} }
} }
} }
@ -572,7 +577,7 @@ public class AccurateMathTest {
final int TOO_BIG_TO_CALCULATE = 18; // This value is empirical: 2^18 > 200.000 resulting bits after raising d to power i. final int TOO_BIG_TO_CALCULATE = 18; // This value is empirical: 2^18 > 200.000 resulting bits after raising d to power i.
for (double d : DOUBLES) { for (double d : DOUBLES) {
if (d % 1.0 == 0.0) { if (d % 1.0 == 0.0) {
boolean dNegative = Double.doubleToRawLongBits( d ) < 0L; boolean dNegative = Double.doubleToRawLongBits(d) < 0L;
for (double i : DOUBLES) { for (double i : DOUBLES) {
if (i % 1.0 == 0.0) { if (i % 1.0 == 0.0) {
BigInteger bd = BigDecimal.valueOf(d).toBigInteger().abs(); BigInteger bd = BigDecimal.valueOf(d).toBigInteger().abs();
@ -588,10 +593,10 @@ public class AccurateMathTest {
} else if (res.signum() == 0) { } else if (res.signum() == 0) {
expected = Double.POSITIVE_INFINITY; expected = Double.POSITIVE_INFINITY;
} else { } else {
expected = BigDecimal.ONE.divide( new BigDecimal( res ), 1024, RoundingMode.HALF_UP ).doubleValue(); expected = BigDecimal.ONE.divide(new BigDecimal(res), 1024, RoundingMode.HALF_UP).doubleValue();
} }
} }
if (dNegative && bi.testBit( 0 )) { if (dNegative && bi.testBit(0)) {
expected = -expected; expected = -expected;
} }
assertEquals(d + "^" + i + "=" + expected + ", Math.pow=" + Math.pow(d, i), expected, AccurateMath.pow(d, i), expected == 0.0 || Double.isInfinite(expected) || Double.isNaN(expected) ? EXACT : 2.0 * Math.ulp(expected)); assertEquals(d + "^" + i + "=" + expected + ", Math.pow=" + Math.pow(d, i), expected, AccurateMath.pow(d, i), expected == 0.0 || Double.isInfinite(expected) || Double.isNaN(expected) ? EXACT : 2.0 * Math.ulp(expected));
@ -641,7 +646,7 @@ public class AccurateMathTest {
AccurateMath.atan2(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), Precision.EPSILON); AccurateMath.atan2(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), Precision.EPSILON);
assertEquals("atan2(-Inf, Inf) should be -PI/4", -AccurateMath.PI / 4.0, AccurateMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), assertEquals("atan2(-Inf, Inf) should be -PI/4", -AccurateMath.PI / 4.0, AccurateMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY),
Precision.EPSILON); Precision.EPSILON);
assertEquals("atan2(-Inf, -Inf) should be -PI * 3/4", - AccurateMath.PI * 3.0 / 4.0, assertEquals("atan2(-Inf, -Inf) should be -PI * 3/4", -AccurateMath.PI * 3.0 / 4.0,
AccurateMath.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY), Precision.EPSILON); AccurateMath.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY), Precision.EPSILON);
} }
@ -891,7 +896,7 @@ public class AccurateMathTest {
public void testAsinAccuracy() { public void testAsinAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = AccurateMath.asin(x); double tst = AccurateMath.asin(x);
@ -914,7 +919,7 @@ public class AccurateMathTest {
public void testAcosAccuracy() { public void testAcosAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = AccurateMath.acos(x); double tst = AccurateMath.acos(x);
@ -962,22 +967,22 @@ public class AccurateMathTest {
} }
private Dfp cosh(Dfp x) { private Dfp cosh(Dfp x) {
return DfpMath.exp(x).add(DfpMath.exp(x.negate())).divide(2); return DfpMath.exp(x).add(DfpMath.exp(x.negate())).divide(2);
} }
private Dfp sinh(Dfp x) { private Dfp sinh(Dfp x) {
return DfpMath.exp(x).subtract(DfpMath.exp(x.negate())).divide(2); return DfpMath.exp(x).subtract(DfpMath.exp(x.negate())).divide(2);
} }
private Dfp tanh(Dfp x) { private Dfp tanh(Dfp x) {
return sinh(x).divide(cosh(x)); return sinh(x).divide(cosh(x));
} }
@Test @Test
public void testSinhAccuracy() { public void testSinhAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = AccurateMath.sinh(x); double tst = AccurateMath.sinh(x);
@ -999,7 +1004,7 @@ public class AccurateMathTest {
public void testCoshAccuracy() { public void testCoshAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = AccurateMath.cosh(x); double tst = AccurateMath.cosh(x);
@ -1021,7 +1026,7 @@ public class AccurateMathTest {
public void testTanhAccuracy() { public void testTanhAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = AccurateMath.tanh(x); double tst = AccurateMath.tanh(x);
@ -1043,7 +1048,7 @@ public class AccurateMathTest {
public void testCbrtAccuracy() { public void testCbrtAccuracy() {
double maxerrulp = 0.0; double maxerrulp = 0.0;
for (int i=0; i<10000; i++) { for (int i = 0; i < 10000; i++) {
double x = ((generator.nextDouble() * 200.0) - 100.0) * generator.nextDouble(); double x = ((generator.nextDouble() * 200.0) - 100.0) * generator.nextDouble();
double tst = AccurateMath.cbrt(x); double tst = AccurateMath.cbrt(x);
@ -1062,7 +1067,7 @@ public class AccurateMathTest {
} }
private Dfp cbrt(Dfp x) { private Dfp cbrt(Dfp x) {
boolean negative=false; boolean negative = false;
if (x.lessThan(field.getZero())) { if (x.lessThan(field.getZero())) {
negative = true; negative = true;
@ -1187,11 +1192,11 @@ public class AccurateMathTest {
@Test @Test
public void testDoubleNextAfterSpecialCases() { public void testDoubleNextAfterSpecialCases() {
assertEquals(-Double.MAX_VALUE,AccurateMath.nextAfter(Double.NEGATIVE_INFINITY, 0D), 0D); assertEquals(-Double.MAX_VALUE, AccurateMath.nextAfter(Double.NEGATIVE_INFINITY, 0D), 0D);
assertEquals(Double.MAX_VALUE,AccurateMath.nextAfter(Double.POSITIVE_INFINITY, 0D), 0D); assertEquals(Double.MAX_VALUE, AccurateMath.nextAfter(Double.POSITIVE_INFINITY, 0D), 0D);
assertEquals(Double.NaN,AccurateMath.nextAfter(Double.NaN, 0D), 0D); assertEquals(Double.NaN, AccurateMath.nextAfter(Double.NaN, 0D), 0D);
assertEquals(Double.POSITIVE_INFINITY,AccurateMath.nextAfter(Double.MAX_VALUE, Double.POSITIVE_INFINITY), 0D); assertEquals(Double.POSITIVE_INFINITY, AccurateMath.nextAfter(Double.MAX_VALUE, Double.POSITIVE_INFINITY), 0D);
assertEquals(Double.NEGATIVE_INFINITY,AccurateMath.nextAfter(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.nextAfter(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), 0D);
assertEquals(Double.MIN_VALUE, AccurateMath.nextAfter(0D, 1D), 0D); assertEquals(Double.MIN_VALUE, AccurateMath.nextAfter(0D, 1D), 0D);
assertEquals(-Double.MIN_VALUE, AccurateMath.nextAfter(0D, -1D), 0D); assertEquals(-Double.MIN_VALUE, AccurateMath.nextAfter(0D, -1D), 0D);
assertEquals(0D, AccurateMath.nextAfter(Double.MIN_VALUE, -1), 0D); assertEquals(0D, AccurateMath.nextAfter(Double.MIN_VALUE, -1), 0D);
@ -1228,11 +1233,11 @@ public class AccurateMathTest {
assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2047), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2047), 0D);
assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2048), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2048), 0D);
assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-1.7976931348623157E308, 2147483647), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-1.7976931348623157E308, 2147483647), 0D);
assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb( 1.7976931348623157E308, 2147483647), 0D); assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb(+1.7976931348623157E308, 2147483647), 0D);
assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-1.1102230246251565E-16, 2147483647), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-1.1102230246251565E-16, 2147483647), 0D);
assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb( 1.1102230246251565E-16, 2147483647), 0D); assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb(+1.1102230246251565E-16, 2147483647), 0D);
assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2147483647), 0D); assertEquals(Double.NEGATIVE_INFINITY, AccurateMath.scalb(-2.2250738585072014E-308, 2147483647), 0D);
assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb( 2.2250738585072014E-308, 2147483647), 0D); assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb(+2.2250738585072014E-308, 2147483647), 0D);
} }
@Test @Test
@ -1253,16 +1258,16 @@ public class AccurateMathTest {
assertEquals(Float.NEGATIVE_INFINITY, AccurateMath.scalb(-3.4028235E38f, 2147483647), 0F); assertEquals(Float.NEGATIVE_INFINITY, AccurateMath.scalb(-3.4028235E38f, 2147483647), 0F);
} }
private boolean compareClassMethods(Class<?> class1, Class<?> class2){ private boolean compareClassMethods(Class<?> class1, Class<?> class2) {
boolean allfound = true; boolean allfound = true;
for(Method method1 : class1.getDeclaredMethods()){ for (Method method1 : class1.getDeclaredMethods()) {
if (Modifier.isPublic(method1.getModifiers())){ if (Modifier.isPublic(method1.getModifiers())) {
Type []params = method1.getGenericParameterTypes(); Type[] params = method1.getGenericParameterTypes();
try { try {
class2.getDeclaredMethod(method1.getName(), (Class[]) params); class2.getDeclaredMethod(method1.getName(), (Class[]) params);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
allfound = false; allfound = false;
System.out.println(class2.getSimpleName()+" does not implement: "+method1); System.out.println(class2.getSimpleName() + " does not implement: " + method1);
} }
} }
} }
@ -1337,10 +1342,10 @@ public class AccurateMathTest {
@Test @Test
public void testIntPow() { public void testIntPow() {
final int maxExp = 300; final int maxExp = 300;
DfpField field = new DfpField(40); DfpField localField = new DfpField(40);
final double base = 1.23456789; final double base = 1.23456789;
Dfp baseDfp = field.newDfp(base); Dfp baseDfp = localField.newDfp(base);
Dfp dfpPower = field.getOne(); Dfp dfpPower = localField.getOne();
for (int i = 0; i < maxExp; i++) { for (int i = 0; i < maxExp; i++) {
assertEquals("exp=" + i, dfpPower.toDouble(), AccurateMath.pow(base, i), assertEquals("exp=" + i, dfpPower.toDouble(), AccurateMath.pow(base, i),
0.6 * AccurateMath.ulp(dfpPower.toDouble())); 0.6 * AccurateMath.ulp(dfpPower.toDouble()));
@ -1353,28 +1358,27 @@ public class AccurateMathTest {
assertTrue(Double.isInfinite(AccurateMath.pow(AccurateMath.scalb(1.0, 500), 4))); assertTrue(Double.isInfinite(AccurateMath.pow(AccurateMath.scalb(1.0, 500), 4)));
} }
@Test(timeout=5000L) // This test must finish in finite time. @Test(timeout = 5000L) // This test must finish in finite time.
public void testIntPowLongMinValue() { public void testIntPowLongMinValue() {
assertEquals(1.0, AccurateMath.pow(1.0, Long.MIN_VALUE), -1.0); assertEquals(1.0, AccurateMath.pow(1.0, Long.MIN_VALUE), -1.0);
} }
@Test(timeout=5000L) @Test(timeout = 5000L)
public void testIntPowSpecialCases() { public void testIntPowSpecialCases() {
final double EXACT = -1.0; final double EXACT = -1.0;
final double DOUBLES[] = new double[] final double[] DOUBLES = new double[] {
{ Double.NEGATIVE_INFINITY, -0.0, Double.NaN, 0.0, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, -0.0, Double.NaN, 0.0, Double.POSITIVE_INFINITY, Long.MIN_VALUE, Integer.MIN_VALUE, Short.MIN_VALUE, Byte.MIN_VALUE,
Long.MIN_VALUE, Integer.MIN_VALUE, Short.MIN_VALUE, Byte.MIN_VALUE, -(double)Long.MIN_VALUE, -(double)Integer.MIN_VALUE, -(double)Short.MIN_VALUE, -(double)Byte.MIN_VALUE,
-(double)Long.MIN_VALUE, -(double)Integer.MIN_VALUE, -(double)Short.MIN_VALUE, -(double)Byte.MIN_VALUE, Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE,
Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE, -Byte.MAX_VALUE, -Short.MAX_VALUE, -Integer.MAX_VALUE, -Long.MAX_VALUE,
-Byte.MAX_VALUE, -Short.MAX_VALUE, -Integer.MAX_VALUE, -Long.MAX_VALUE, Float.MAX_VALUE, Double.MAX_VALUE, Double.MIN_VALUE, Float.MIN_VALUE,
Float.MAX_VALUE, Double.MAX_VALUE, Double.MIN_VALUE, Float.MIN_VALUE, -Float.MAX_VALUE, -Double.MAX_VALUE, -Double.MIN_VALUE, -Float.MIN_VALUE,
-Float.MAX_VALUE, -Double.MAX_VALUE, -Double.MIN_VALUE, -Float.MIN_VALUE, 0.5, 0.1, 0.2, 0.8, 1.1, 1.2, 1.5, 1.8, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.3, 2.2, 2.5, 2.8, 33.0, 33.1, 33.5, 33.8, 10.0, 300.0, 400.0, 500.0,
0.5, 0.1, 0.2, 0.8, 1.1, 1.2, 1.5, 1.8, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.3, 2.2, 2.5, 2.8, 33.0, 33.1, 33.5, 33.8, 10.0, 300.0, 400.0, 500.0, -0.5, -0.1, -0.2, -0.8, -1.1, -1.2, -1.5, -1.8, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -1.3, -2.2, -2.5, -2.8, -33.0, -33.1, -33.5, -33.8, -10.0, -300.0, -400.0, -500.0
-0.5, -0.1, -0.2, -0.8, -1.1, -1.2, -1.5, -1.8, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0, -1.3, -2.2, -2.5, -2.8, -33.0, -33.1, -33.5, -33.8, -10.0, -300.0, -400.0, -500.0 };
};
final long INTS[] = new long[]{Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE + 2, Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 2, 0, 1, 2, 3, 5, 8, 10, 20, 100, 300, 500, -1, -2, -3, -5, -8, -10, -20, -100, -300, -500}; final long[] INTS = new long[]{Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE + 2, Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 2, 0, 1, 2, 3, 5, 8, 10, 20, 100, 300, 500, -1, -2, -3, -5, -8, -10, -20, -100, -300, -500};
// Special cases from Math.pow javadoc: // Special cases from Math.pow javadoc:
// If the second argument is positive or negative zero, then the result is 1.0. // If the second argument is positive or negative zero, then the result is 1.0.
for (double d : DOUBLES) { for (double d : DOUBLES) {
@ -1515,9 +1519,12 @@ public class AccurateMathTest {
if (d < 0.0 && Math.abs(d) <= Double.MAX_VALUE) { if (d < 0.0 && Math.abs(d) <= Double.MAX_VALUE) {
for (long i : INTS) { for (long i : INTS) {
// if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument // if the second argument is a finite even integer, the result is equal to the result of raising the absolute value of the first argument to the power of the second argument
if ((i & 1L) == 0L) assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT); if ((i & 1L) == 0L) {
// if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
else assertEquals(-AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT); } else {
// if the second argument is a finite odd integer, the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument
assertEquals(-AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
}
// if the second argument is finite and not an integer, then the result is NaN. <- Impossible with int. // if the second argument is finite and not an integer, then the result is NaN. <- Impossible with int.
} }
} }
@ -1752,23 +1759,23 @@ public class AccurateMathTest {
} }
} }
@Test(expected=MathArithmeticException.class) @Test(expected = MathArithmeticException.class)
public void testToIntExactTooLow() { public void testToIntExactTooLow() {
AccurateMath.toIntExact(-1l + Integer.MIN_VALUE); AccurateMath.toIntExact(-1L + Integer.MIN_VALUE);
} }
@Test(expected=MathArithmeticException.class) @Test(expected = MathArithmeticException.class)
public void testToIntExactTooHigh() { public void testToIntExactTooHigh() {
AccurateMath.toIntExact(+1l + Integer.MAX_VALUE); AccurateMath.toIntExact(+1L + Integer.MAX_VALUE);
} }
@Test @Test
public void testToIntExact() { public void testToIntExact() {
for (int n = -1000; n < 1000; ++n) { for (int n = -1000; n < 1000; ++n) {
assertEquals(n, AccurateMath.toIntExact(0l + n)); assertEquals(n, AccurateMath.toIntExact(0L + n));
} }
assertEquals(Integer.MIN_VALUE, AccurateMath.toIntExact(0l + Integer.MIN_VALUE)); assertEquals(Integer.MIN_VALUE, AccurateMath.toIntExact(0L + Integer.MIN_VALUE));
assertEquals(Integer.MAX_VALUE, AccurateMath.toIntExact(0l + Integer.MAX_VALUE)); assertEquals(Integer.MAX_VALUE, AccurateMath.toIntExact(0L + Integer.MAX_VALUE));
} }
@Test @Test
@ -1815,11 +1822,11 @@ public class AccurateMathTest {
@Test @Test
public void testFloorDivModInt() { public void testFloorDivModInt() {
UniformRandomProvider generator = RandomSource.create(RandomSource.WELL_1024_A, UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_1024_A,
0x7ccab45edeaab90al); 0x7ccab45edeaab90aL);
for (int i = 0; i < 10000; ++i) { for (int i = 0; i < 10000; ++i) {
int a = generator.nextInt(); int a = rng.nextInt();
int b = generator.nextInt(); int b = rng.nextInt();
if (b == 0) { if (b == 0) {
try { try {
AccurateMath.floorDiv(a, b); AccurateMath.floorDiv(a, b);
@ -1846,18 +1853,18 @@ public class AccurateMathTest {
@Test @Test
public void testFloorDivLong() { public void testFloorDivLong() {
assertEquals(+1l, AccurateMath.floorDiv(+4l, +3l)); assertEquals(+1L, AccurateMath.floorDiv(+4L, +3L));
assertEquals(-2l, AccurateMath.floorDiv(-4l, +3l)); assertEquals(-2L, AccurateMath.floorDiv(-4L, +3L));
assertEquals(-2l, AccurateMath.floorDiv(+4l, -3l)); assertEquals(-2L, AccurateMath.floorDiv(+4L, -3L));
assertEquals(+1l, AccurateMath.floorDiv(-4l, -3l)); assertEquals(+1L, AccurateMath.floorDiv(-4L, -3L));
try { try {
AccurateMath.floorDiv(1l, 0l); AccurateMath.floorDiv(1L, 0L);
fail("an exception should have been thrown"); fail("an exception should have been thrown");
} catch (MathArithmeticException mae) { } catch (MathArithmeticException mae) {
// expected // expected
} }
for (long a = -100l; a <= 100l; ++a) { for (long a = -100L; a <= 100L; ++a) {
for (long b = -100l; b <= 100l; ++b) { for (long b = -100L; b <= 100L; ++b) {
if (b != 0) { if (b != 0) {
assertEquals(poorManFloorDiv(a, b), AccurateMath.floorDiv(a, b)); assertEquals(poorManFloorDiv(a, b), AccurateMath.floorDiv(a, b));
} }
@ -1867,18 +1874,18 @@ public class AccurateMathTest {
@Test @Test
public void testFloorModLong() { public void testFloorModLong() {
assertEquals(+1l, AccurateMath.floorMod(+4l, +3l)); assertEquals(+1L, AccurateMath.floorMod(+4L, +3L));
assertEquals(+2l, AccurateMath.floorMod(-4l, +3l)); assertEquals(+2L, AccurateMath.floorMod(-4L, +3L));
assertEquals(-2l, AccurateMath.floorMod(+4l, -3l)); assertEquals(-2L, AccurateMath.floorMod(+4L, -3L));
assertEquals(-1l, AccurateMath.floorMod(-4l, -3l)); assertEquals(-1L, AccurateMath.floorMod(-4L, -3L));
try { try {
AccurateMath.floorMod(1l, 0l); AccurateMath.floorMod(1L, 0L);
fail("an exception should have been thrown"); fail("an exception should have been thrown");
} catch (MathArithmeticException mae) { } catch (MathArithmeticException mae) {
// expected // expected
} }
for (long a = -100l; a <= 100l; ++a) { for (long a = -100L; a <= 100L; ++a) {
for (long b = -100l; b <= 100l; ++b) { for (long b = -100L; b <= 100L; ++b) {
if (b != 0) { if (b != 0) {
assertEquals(poorManFloorMod(a, b), AccurateMath.floorMod(a, b)); assertEquals(poorManFloorMod(a, b), AccurateMath.floorMod(a, b));
} }
@ -1888,11 +1895,11 @@ public class AccurateMathTest {
@Test @Test
public void testFloorDivModLong() { public void testFloorDivModLong() {
UniformRandomProvider generator = RandomSource.create(RandomSource.WELL_1024_A, UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_1024_A,
0xb87b9bc14c96ccd5l); 0xb87b9bc14c96ccd5L);
for (int i = 0; i < 10000; ++i) { for (int i = 0; i < 10000; ++i) {
long a = generator.nextLong(); long a = rng.nextLong();
long b = generator.nextLong(); long b = rng.nextLong();
if (b == 0) { if (b == 0) {
try { try {
AccurateMath.floorDiv(a, b); AccurateMath.floorDiv(a, b);
@ -1931,7 +1938,7 @@ public class AccurateMathTest {
BigInteger q = q0.subtract(bigK); BigInteger q = q0.subtract(bigK);
BigInteger r = r0.add(bigK.multiply(bigB)); BigInteger r = r0.add(bigK.multiply(bigB));
if (r.abs().compareTo(bigB.abs()) < 0 && if (r.abs().compareTo(bigB.abs()) < 0 &&
(r.longValue() == 0l || ((r.longValue() ^ b) & 0x8000000000000000l) == 0)) { (r.longValue() == 0L || ((r.longValue() ^ b) & 0x8000000000000000L) == 0)) {
if (fd.compareTo(q) < 0) { if (fd.compareTo(q) < 0) {
fd = q; fd = q;
} }

View File

@ -43,7 +43,7 @@ public class ConvergenceException extends MathIllegalStateException {
* the error. * the error.
* @param args Arguments. * @param args Arguments.
*/ */
public ConvergenceException(Localizable pattern, Object ... args) { public ConvergenceException(Localizable pattern, Object... args) {
getContext().addMessage(pattern, args); getContext().addMessage(pattern, args);
} }
} }

View File

@ -45,7 +45,7 @@ public class MathArithmeticException extends MathRuntimeException {
* the error. * the error.
* @param args Arguments. * @param args Arguments.
*/ */
public MathArithmeticException(Localizable pattern, Object ... args) { public MathArithmeticException(Localizable pattern, Object... args) {
super(pattern, args); super(pattern, args);
} }

View File

@ -34,7 +34,7 @@ public class MathIllegalArgumentException extends MathRuntimeException {
* @param pattern Message pattern explaining the cause of the error. * @param pattern Message pattern explaining the cause of the error.
* @param args Arguments. * @param args Arguments.
*/ */
public MathIllegalArgumentException(Localizable pattern, Object ... args) { public MathIllegalArgumentException(Localizable pattern, Object... args) {
super(pattern, args); super(pattern, args);
} }

View File

@ -46,7 +46,7 @@ public class MathIllegalNumberException extends MathIllegalArgumentException {
*/ */
protected MathIllegalNumberException(Localizable pattern, protected MathIllegalNumberException(Localizable pattern,
Number wrong, Number wrong,
Object ... arguments) { Object... arguments) {
super(pattern, wrong, arguments); super(pattern, wrong, arguments);
argument = wrong; argument = wrong;
} }

View File

@ -36,7 +36,7 @@ public class MathIllegalStateException extends MathRuntimeException {
* @param pattern Message pattern explaining the cause of the error. * @param pattern Message pattern explaining the cause of the error.
* @param args Arguments. * @param args Arguments.
*/ */
public MathIllegalStateException(Localizable pattern, Object ... args) { public MathIllegalStateException(Localizable pattern, Object... args) {
super(pattern, args); super(pattern, args);
} }
@ -49,7 +49,7 @@ public class MathIllegalStateException extends MathRuntimeException {
*/ */
public MathIllegalStateException(Throwable cause, public MathIllegalStateException(Throwable cause,
Localizable pattern, Localizable pattern,
Object ... args) { Object... args) {
super(cause, pattern, args); super(cause, pattern, args);
} }

View File

@ -51,7 +51,7 @@ public class MathInternalError extends MathIllegalStateException {
* @param pattern Message pattern explaining the cause of the error. * @param pattern Message pattern explaining the cause of the error.
* @param args Arguments. * @param args Arguments.
*/ */
public MathInternalError(Localizable pattern, Object ... args) { public MathInternalError(Localizable pattern, Object... args) {
super(pattern, args); super(pattern, args);
} }
} }

View File

@ -41,7 +41,7 @@ public class MathRuntimeException extends RuntimeException
* @param args Arguments. * @param args Arguments.
*/ */
public MathRuntimeException(Localizable pattern, public MathRuntimeException(Localizable pattern,
Object ... args) { Object... args) {
context = new ExceptionContext(this); context = new ExceptionContext(this);
context.addMessage(pattern, args); context.addMessage(pattern, args);
} }
@ -54,7 +54,7 @@ public class MathRuntimeException extends RuntimeException
*/ */
public MathRuntimeException(Throwable cause, public MathRuntimeException(Throwable cause,
Localizable pattern, Localizable pattern,
Object ... args) { Object... args) {
super(cause); super(cause);
context = new ExceptionContext(this); context = new ExceptionContext(this);
context.addMessage(pattern, args); context.addMessage(pattern, args);

View File

@ -42,7 +42,7 @@ public class MathUnsupportedOperationException extends MathRuntimeException {
* the error. * the error.
* @param args Arguments. * @param args Arguments.
*/ */
public MathUnsupportedOperationException(Localizable pattern, Object ... args) { public MathUnsupportedOperationException(Localizable pattern, Object... args) {
super(pattern, args); super(pattern, args);
} }

View File

@ -49,7 +49,7 @@ public class MaxCountExceededException extends MathIllegalStateException {
*/ */
public MaxCountExceededException(Localizable specific, public MaxCountExceededException(Localizable specific,
Number max, Number max,
Object ... args) { Object... args) {
getContext().addMessage(specific, max, args); getContext().addMessage(specific, max, args);
this.max = max; this.max = max;
} }

View File

@ -63,7 +63,7 @@ public class NoBracketingException extends MathIllegalArgumentException {
public NoBracketingException(Localizable specific, public NoBracketingException(Localizable specific,
double lo, double hi, double lo, double hi,
double fLo, double fHi, double fLo, double fHi,
Object ... args) { Object... args) {
super(specific, Double.valueOf(lo), Double.valueOf(hi), Double.valueOf(fLo), Double.valueOf(fHi), args); super(specific, Double.valueOf(lo), Double.valueOf(hi), Double.valueOf(fLo), Double.valueOf(fHi), args);
this.lo = lo; this.lo = lo;
this.hi = hi; this.hi = hi;

View File

@ -35,7 +35,7 @@ public class NotFiniteNumberException extends MathIllegalNumberException {
* @param args Optional arguments. * @param args Optional arguments.
*/ */
public NotFiniteNumberException(Number wrong, public NotFiniteNumberException(Number wrong,
Object ... args) { Object... args) {
this(LocalizedFormats.NOT_FINITE_NUMBER, wrong, args); this(LocalizedFormats.NOT_FINITE_NUMBER, wrong, args);
} }
@ -48,7 +48,7 @@ public class NotFiniteNumberException extends MathIllegalNumberException {
*/ */
public NotFiniteNumberException(Localizable specific, public NotFiniteNumberException(Localizable specific,
Number wrong, Number wrong,
Object ... args) { Object... args) {
super(specific, wrong, args); super(specific, wrong, args);
} }

View File

@ -55,7 +55,7 @@ public class NullArgumentException extends NullPointerException
* @param arguments Values for replacing the placeholders in {@code pattern}. * @param arguments Values for replacing the placeholders in {@code pattern}.
*/ */
public NullArgumentException(Localizable pattern, public NullArgumentException(Localizable pattern,
Object ... arguments) { Object... arguments) {
context = new ExceptionContext(this); context = new ExceptionContext(this);
context.addMessage(pattern, arguments); context.addMessage(pattern, arguments);
} }
@ -91,7 +91,7 @@ public class NullArgumentException extends NullPointerException
*/ */
public static void check(Object o, public static void check(Object o,
Localizable pattern, Localizable pattern,
Object ... args) { Object... args) {
if (o == null) { if (o == null) {
throw new NullArgumentException(pattern, args); throw new NullArgumentException(pattern, args);
} }

View File

@ -26,7 +26,7 @@ import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
*/ */
public class ZeroException extends MathIllegalNumberException { public class ZeroException extends MathIllegalNumberException {
/** Serializable version identifier */ /** Serializable version identifier. */
private static final long serialVersionUID = -1960874856936000015L; private static final long serialVersionUID = -1960874856936000015L;
/** /**
@ -42,7 +42,7 @@ public class ZeroException extends MathIllegalNumberException {
* @param specific Specific context pattern. * @param specific Specific context pattern.
* @param arguments Arguments. * @param arguments Arguments.
*/ */
public ZeroException(Localizable specific, Object ... arguments) { public ZeroException(Localizable specific, Object... arguments) {
super(specific, INTEGER_ZERO, arguments); super(specific, INTEGER_ZERO, arguments);
} }
} }

View File

@ -23,9 +23,8 @@ import java.util.ArrayList;
/** /**
* Utility class for transforming the list of arguments passed to * Utility class for transforming the list of arguments passed to
* constructors of exceptions. * constructors of exceptions.
*
*/ */
public class ArgUtils { public final class ArgUtils {
/** /**
* Class contains only static methods. * Class contains only static methods.
*/ */

View File

@ -82,7 +82,7 @@ public class ExceptionContext implements Serializable {
* pattern. * pattern.
*/ */
public void addMessage(Localizable pattern, public void addMessage(Localizable pattern,
Object ... arguments) { Object... arguments) {
msgPatterns.add(pattern); msgPatterns.add(pattern);
msgArguments.add(ArgUtils.flatten(arguments)); msgArguments.add(ArgUtils.flatten(arguments));
} }
@ -110,7 +110,7 @@ public class ExceptionContext implements Serializable {
} }
/** /**
* Gets all the keys stored in the exception * Gets all the keys stored in the exception.
* *
* @return the set of keys. * @return the set of keys.
*/ */
@ -285,7 +285,7 @@ public class ExceptionContext implements Serializable {
// Step 1. // Step 1.
final int len = context.size(); final int len = context.size();
out.writeInt(len); out.writeInt(len);
for (Map.Entry<String,Object> entry : context.entrySet()) { for (Map.Entry<String, Object> entry : context.entrySet()) {
// Step 2. // Step 2.
out.writeObject(entry.getKey()); out.writeObject(entry.getKey());
final Object value = entry.getValue(); final Object value = entry.getValue();
@ -328,7 +328,7 @@ public class ExceptionContext implements Serializable {
* interface. * interface.
* @return a string that mentions which class could not be serialized. * @return a string that mentions which class could not be serialized.
*/ */
private String nonSerializableReplacement(Object obj) { private static String nonSerializableReplacement(Object obj) {
return "[Object could not be serialized: " + obj.getClass().getName() + "]"; return "[Object could not be serialized: " + obj.getClass().getName() + "]";
} }
} }

View File

@ -1,23 +1,24 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this * contributor license agreements. See the NOTICE file distributed with
* work for additional information regarding copyright ownership. The ASF * this work for additional information regarding copyright ownership.
* licenses this file to You under the Apache License, Version 2.0 (the * The ASF licenses this file to You under the Apache License, Version 2.0
* "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with
* You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law *
* or agreed to in writing, software distributed under the License is * http://www.apache.org/licenses/LICENSE-2.0
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the specific language * Unless required by applicable law or agreed to in writing, software
* governing permissions and limitations under the License. * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.apache.commons.math4.legacy.exception; package org.apache.commons.math4.legacy.exception;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
/** /**
* Tests for {@link NotFiniteNumberException}. * Tests for {@link NotFiniteNumberException}.
*/ */

View File

@ -1,19 +1,21 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this * contributor license agreements. See the NOTICE file distributed with
* work for additional information regarding copyright ownership. The ASF * this work for additional information regarding copyright ownership.
* licenses this file to You under the Apache License, Version 2.0 (the * The ASF licenses this file to You under the Apache License, Version 2.0
* "License"); you may not use this file except in compliance with the License. * (the "License"); you may not use this file except in compliance with
* You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law *
* or agreed to in writing, software distributed under the License is * http://www.apache.org/licenses/LICENSE-2.0
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the specific language * Unless required by applicable law or agreed to in writing, software
* governing permissions and limitations under the License. * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.apache.commons.math4.legacy.exception; package org.apache.commons.math4.legacy.exception;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.apache.commons.math4.legacy.exception.util.LocalizedFormats; import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;

View File

@ -107,18 +107,16 @@ public class ExceptionContextTest {
String key = "Key 1"; String key = "Key 1";
cOut.setValue(key, new Unserializable()); cOut.setValue(key, new Unserializable());
{ ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos);
ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(cOut);
oos.writeObject(cOut);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis); ObjectInputStream ois = new ObjectInputStream(bis);
ExceptionContext cIn = (ExceptionContext) ois.readObject(); ExceptionContext cIn = (ExceptionContext) ois.readObject();
String nsObjStr = (String) cIn.getValue(key); String nsObjStr = (String) cIn.getValue(key);
Assert.assertTrue(nsObjStr.matches(".*could not be serialized.*")); Assert.assertTrue(nsObjStr.matches(".*could not be serialized.*"));
}
} }
/** /**

View File

@ -35,7 +35,7 @@ public class LocalizedFormatsTest {
@Test @Test
public void testAllKeysPresentInPropertiesFiles() { public void testAllKeysPresentInPropertiesFiles() {
final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/"); final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/");
for (final String language : new String[] { "fr" } ) { for (final String language : new String[] {"fr"}) {
ResourceBundle bundle = ResourceBundle bundle =
ResourceBundle.getBundle("assets/" + path, new Locale(language)); ResourceBundle.getBundle("assets/" + path, new Locale(language));
for (LocalizedFormats message : LocalizedFormats.values()) { for (LocalizedFormats message : LocalizedFormats.values()) {
@ -55,7 +55,7 @@ public class LocalizedFormatsTest {
@Test @Test
public void testAllPropertiesCorrespondToKeys() { public void testAllPropertiesCorrespondToKeys() {
final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/"); final String path = LocalizedFormats.class.getName().replaceAll("\\.", "/");
for (final String language : new String[] { "fr" } ) { for (final String language : new String[] {"fr"}) {
ResourceBundle bundle = ResourceBundle bundle =
ResourceBundle.getBundle("assets/" + path, new Locale(language)); ResourceBundle.getBundle("assets/" + path, new Locale(language));
for (final Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) { for (final Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) {
@ -89,7 +89,7 @@ public class LocalizedFormatsTest {
@Test @Test
public void testVariablePartsConsistency() { public void testVariablePartsConsistency() {
for (final String language : new String[] { "fr" } ) { for (final String language : new String[] {"fr"}) {
Locale locale = new Locale(language); Locale locale = new Locale(language);
for (LocalizedFormats message : LocalizedFormats.values()) { for (LocalizedFormats message : LocalizedFormats.values()) {
MessageFormat source = new MessageFormat(message.getSourceString()); MessageFormat source = new MessageFormat(message.getSourceString());

View File

@ -145,6 +145,14 @@
<skip>true</skip> <skip>true</skip>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>${math.parent.dir}/src/main/resources/checkstyle/checkstyle-legacy.xml</configLocation>
<suppressionsLocation>${math.parent.dir}/src/main/resources/checkstyle/checkstyle-suppressions-legacy.xml</suppressionsLocation>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -24,4 +24,6 @@ import java.util.function.ToDoubleBiFunction;
* *
* @since 4.0 * @since 4.0
*/ */
public interface DistanceMeasure extends ToDoubleBiFunction<double[],double[]> {} public interface DistanceMeasure extends ToDoubleBiFunction<double[], double[]> {
// Convenience interface
}

View File

@ -20,7 +20,6 @@ package org.apache.commons.math4.neuralnet;
import java.util.function.DoubleUnaryOperator; import java.util.function.DoubleUnaryOperator;
import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler; import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler;
/** /**
@ -29,7 +28,7 @@ import org.apache.commons.rng.sampling.distribution.ContinuousUniformSampler;
* *
* @since 3.3 * @since 3.3
*/ */
public class FeatureInitializerFactory { public final class FeatureInitializerFactory {
/** Class contains only static methods. */ /** Class contains only static methods. */
private FeatureInitializerFactory() {} private FeatureInitializerFactory() {}
@ -48,7 +47,7 @@ public class FeatureInitializerFactory {
final double min, final double min,
final double max) { final double max) {
return randomize(new ContinuousUniformSampler(rng, min, max), return randomize(new ContinuousUniformSampler(rng, min, max),
function((x) -> 0, 0, 0)); function(x -> 0, 0, 0));
} }
/** /**

View File

@ -123,13 +123,13 @@ public class MapRanking {
/** Comparator. */ /** Comparator. */
static final Comparator<PairNeuronDouble> COMPARATOR static final Comparator<PairNeuronDouble> COMPARATOR
= new Comparator<PairNeuronDouble>() { = new Comparator<PairNeuronDouble>() {
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override @Override
public int compare(PairNeuronDouble o1, public int compare(PairNeuronDouble o1,
PairNeuronDouble o2) { PairNeuronDouble o2) {
return Double.compare(o1.value, o2.value); return Double.compare(o1.value, o2.value);
} }
}; };
/** Key. */ /** Key. */
private final Neuron neuron; private final Neuron neuron;
/** Value. */ /** Value. */

View File

@ -26,7 +26,7 @@ import org.apache.commons.math4.neuralnet.internal.NeuralNetException;
* *
* @since 3.3 * @since 3.3
*/ */
public class MapUtils { public final class MapUtils {
/** /**
* Class contains only static methods. * Class contains only static methods.
*/ */

View File

@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal utility classes.
*/
package org.apache.commons.math4.neuralnet.internal;

View File

@ -31,7 +31,7 @@ import org.apache.commons.math4.neuralnet.Network;
* @since 3.3 * @since 3.3
*/ */
public class NeuronString implements Serializable { public class NeuronString implements Serializable {
/** Serial version ID */ /** Serial version ID. */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** Underlying network. */ /** Underlying network. */
private final Network network; private final Network network;

View File

@ -240,8 +240,8 @@ public class KohonenUpdateAction implements UpdateAction {
* @param norm Normalization factor. * @param norm Normalization factor.
* @param sigma Standard deviation. * @param sigma Standard deviation.
*/ */
public Gaussian(double norm, Gaussian(double norm,
double sigma) { double sigma) {
this.norm = norm; this.norm = norm;
i2s2 = 1d / (2 * sigma * sigma); i2s2 = 1d / (2 * sigma * sigma);
} }

View File

@ -26,7 +26,7 @@ import org.apache.commons.math4.neuralnet.sofm.util.QuasiSigmoidDecayFunction;
* *
* @since 3.3 * @since 3.3
*/ */
public class LearningFactorFunctionFactory { public final class LearningFactorFunctionFactory {
/** Class contains only static methods. */ /** Class contains only static methods. */
private LearningFactorFunctionFactory() {} private LearningFactorFunctionFactory() {}

View File

@ -25,7 +25,7 @@ import org.apache.commons.math4.neuralnet.sofm.util.QuasiSigmoidDecayFunction;
* *
* @since 3.3 * @since 3.3
*/ */
public class NeighbourhoodSizeFunctionFactory { public final class NeighbourhoodSizeFunctionFactory {
/** Class contains only static methods. */ /** Class contains only static methods. */
private NeighbourhoodSizeFunctionFactory() {} private NeighbourhoodSizeFunctionFactory() {}

View File

@ -66,7 +66,7 @@ public class QuasiSigmoidDecayFunction implements LongToDoubleFunction {
final double k = initValue; final double k = initValue;
final double m = numCall; final double m = numCall;
final double b = 4 * slope / initValue; final double b = 4 * slope / initValue;
sigmoid = (x) -> k / (1 + Math.exp(b * (m - x))); sigmoid = x -> k / (1 + Math.exp(b * (m - x)));
final double y0 = sigmoid.applyAsDouble(0d); final double y0 = sigmoid.applyAsDouble(0d);
scale = k / y0; scale = k / y0;

View File

@ -48,7 +48,7 @@ import org.apache.commons.math4.neuralnet.twod.util.LocationFinder;
public class NeuronSquareMesh2D public class NeuronSquareMesh2D
implements Iterable<Neuron>, implements Iterable<Neuron>,
Serializable { Serializable {
/** Serial version ID */ /** Serial version ID. */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** Underlying network. */ /** Underlying network. */
private final Network network; private final Network network;
@ -430,9 +430,9 @@ public class NeuronSquareMesh2D
colIndex >= numberOfColumns) { colIndex >= numberOfColumns) {
return null; return null;
} else { } else {
return new int[] { rowIndex, colIndex }; return new int[] {rowIndex, colIndex};
} }
} }
/** /**
* Creates the neighbour relationships between neurons. * Creates the neighbour relationships between neurons.
@ -492,12 +492,12 @@ public class NeuronSquareMesh2D
linkEnd.add(identifiers[i + 1][jLast]); linkEnd.add(identifiers[i + 1][jLast]);
} }
} else if (j == jLast) { } else if (j == jLast) {
if (i > 0) { if (i > 0) {
linkEnd.add(identifiers[i - 1][0]); linkEnd.add(identifiers[i - 1][0]);
} }
if (i < iLast) { if (i < iLast) {
linkEnd.add(identifiers[i + 1][0]); linkEnd.add(identifiers[i + 1][0]);
} }
} }
} }
if (wrapRows && if (wrapRows &&
@ -643,7 +643,7 @@ public class NeuronSquareMesh2D
} }
/** /**
* Miscellaneous indicators of the map quality: * Miscellaneous indicators of the map quality.
* <ul> * <ul>
* <li>Hit histogram</li> * <li>Hit histogram</li>
* <li>Quantization error</li> * <li>Quantization error</li>
@ -651,7 +651,7 @@ public class NeuronSquareMesh2D
* <li>Unified distance matrix</li> * <li>Unified distance matrix</li>
* </ul> * </ul>
*/ */
public static class DataVisualization { public static final class DataVisualization {
/** Distance function. */ /** Distance function. */
private static final DistanceMeasure DISTANCE = new EuclideanDistance(); private static final DistanceMeasure DISTANCE = new EuclideanDistance();
/** Total number of samples. */ /** Total number of samples. */
@ -772,7 +772,7 @@ public class NeuronSquareMesh2D
/** /**
* @return the total number of samples. * @return the total number of samples.
*/ */
public final int getNumberOfSamples() { public int getNumberOfSamples() {
return numberOfSamples; return numberOfSamples;
} }
@ -851,8 +851,8 @@ public class NeuronSquareMesh2D
* @param normalizedHits Hits histogram (normalized). * @param normalizedHits Hits histogram (normalized).
* @return the hit-weighted mean of the given {@code metrics}. * @return the hit-weighted mean of the given {@code metrics}.
*/ */
private double hitWeightedMean(double[][] metrics, private static double hitWeightedMean(double[][] metrics,
double[][] normalizedHits) { double[][] normalizedHits) {
double mean = 0; double mean = 0;
final int rows = metrics.length; final int rows = metrics.length;
final int cols = metrics[0].length; final int cols = metrics[0].length;

View File

@ -34,7 +34,7 @@ import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
* unit of the 2D-map. * unit of the 2D-map.
* *
* @since 3.6 * @since 3.6
* @see NeuronSquareMesh2D.DataVisualization#getUMatrix() * @see org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D.DataVisualization#getUMatrix()
*/ */
public class UnifiedDistanceMatrix implements MapVisualization { public class UnifiedDistanceMatrix implements MapVisualization {
/** Distance. */ /** Distance. */

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -43,7 +43,7 @@ public class MapRankingTest {
final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64); final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
final FeatureInitializer init final FeatureInitializer init
= new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, -0.1, 0.1)); = new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, -0.1, 0.1));
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final MapRanking ranking = new MapRanking(new NeuronString(3, false, initArray).getNetwork(), final MapRanking ranking = new MapRanking(new NeuronString(3, false, initArray).getNetwork(),
new EuclideanDistance()); new EuclideanDistance());
@ -60,8 +60,8 @@ public class MapRankingTest {
best.clear(); best.clear();
features = new double[][] { features = new double[][] {
{ -1 }, {-1 },
{ 0.4 }, {0.4 },
}; };
for (double[] f : features) { for (double[] f : features) {
best.addAll(ranking.rank(f, 1)); best.addAll(ranking.rank(f, 1));
@ -71,8 +71,8 @@ public class MapRankingTest {
best.clear(); best.clear();
features = new double[][] { features = new double[][] {
{ 0.6 }, {0.6 },
{ 1.4 }, {1.4 },
}; };
for (double[] f : features) { for (double[] f : features) {
best.addAll(ranking.rank(f, 1)); best.addAll(ranking.rank(f, 1));
@ -82,8 +82,8 @@ public class MapRankingTest {
best.clear(); best.clear();
features = new double[][] { features = new double[][] {
{ 1.6 }, {1.6 },
{ 3 }, {3 },
}; };
for (double[] f : features) { for (double[] f : features) {
best.addAll(ranking.rank(f, 1)); best.addAll(ranking.rank(f, 1));
@ -94,15 +94,15 @@ public class MapRankingTest {
Assert.assertEquals(3, allBest.size()); Assert.assertEquals(3, allBest.size());
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testRankPrecondition() { public void testRankPrecondition() {
final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64); final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
final FeatureInitializer init final FeatureInitializer init
= new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, -0.1, 0.1)); = new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, -0.1, 0.1));
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
new MapRanking(new NeuronString(3, false, initArray).getNetwork(), new MapRanking(new NeuronString(3, false, initArray).getNetwork(),
new EuclideanDistance()).rank(new double[] { -1 }, 0); new EuclideanDistance()).rank(new double[] {-1}, 0);
} }
@Test @Test
@ -110,13 +110,13 @@ public class MapRankingTest {
final Set<Neuron> list = new HashSet<>(); final Set<Neuron> list = new HashSet<>();
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
list.add(new Neuron(i, new double[] { i - 0.5 })); list.add(new Neuron(i, new double[] {i - 0.5}));
} }
final MapRanking rank = new MapRanking(list, new EuclideanDistance()); final MapRanking rank = new MapRanking(list, new EuclideanDistance());
final List<Neuron> sorted = rank.rank(new double[] { 3.4 }); final List<Neuron> sorted = rank.rank(new double[] {3.4});
final long[] expected = new long[] { 3, 2, 1, 0 }; final long[] expected = new long[] {3, 2, 1, 0};
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
Assert.assertEquals(expected[i], sorted.get(i).getIdentifier()); Assert.assertEquals(expected[i], sorted.get(i).getIdentifier());
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -42,7 +42,7 @@ public class NetworkTest {
@Test @Test
public void testGetFeaturesSize() { public void testGetFeaturesSize() {
final FeatureInitializer[] initArray = { init, init, init }; final FeatureInitializer[] initArray = {init, init, init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
@ -61,7 +61,7 @@ public class NetworkTest {
*/ */
@Test @Test
public void testDeleteLink() { public void testDeleteLink() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -90,7 +90,7 @@ public class NetworkTest {
*/ */
@Test @Test
public void testDeleteNeuron() { public void testDeleteNeuron() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -104,7 +104,9 @@ public class NetworkTest {
try { try {
net.getNeuron(1); net.getNeuron(1);
} catch (NoSuchElementException expected) {} } catch (NoSuchElementException expected) {
// Ignore
}
Assert.assertEquals(1, net.getNeighbours(net.getNeuron(0)).size()); Assert.assertEquals(1, net.getNeighbours(net.getNeuron(0)).size());
Assert.assertEquals(1, net.getNeighbours(net.getNeuron(3)).size()); Assert.assertEquals(1, net.getNeighbours(net.getNeuron(3)).size());
@ -112,7 +114,7 @@ public class NetworkTest {
@Test @Test
public void testIterationOrder() { public void testIterationOrder() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(4, false, final Network net = new NeuronSquareMesh2D(4, false,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -142,7 +144,7 @@ public class NetworkTest {
*/ */
@Test @Test
public void testCopy() { public void testCopy() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -177,7 +179,7 @@ public class NetworkTest {
public void testSerialize() public void testSerialize()
throws IOException, throws IOException,
ClassNotFoundException { ClassNotFoundException {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network out = new NeuronSquareMesh2D(4, false, final Network out = new NeuronSquareMesh2D(4, false,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -33,21 +33,21 @@ public class NeuronTest {
@Test @Test
public void testGetIdentifier() { public void testGetIdentifier() {
final long id = 1234567; final long id = 1234567;
final Neuron n = new Neuron(id, new double[] { 0 }); final Neuron n = new Neuron(id, new double[] {0 });
Assert.assertEquals(id, n.getIdentifier()); Assert.assertEquals(id, n.getIdentifier());
} }
@Test @Test
public void testGetSize() { public void testGetSize() {
final double[] features = { -1, -1e-97, 0, 23.456, 9.01e203 } ; final double[] features = {-1, -1e-97, 0, 23.456, 9.01e203};
final Neuron n = new Neuron(1, features); final Neuron n = new Neuron(1, features);
Assert.assertEquals(features.length, n.getSize()); Assert.assertEquals(features.length, n.getSize());
} }
@Test @Test
public void testGetFeatures() { public void testGetFeatures() {
final double[] features = { -1, -1e-97, 0, 23.456, 9.01e203 } ; final double[] features = {-1, -1e-97, 0, 23.456, 9.01e203};
final Neuron n = new Neuron(1, features); final Neuron n = new Neuron(1, features);
final double[] f = n.getFeatures(); final double[] f = n.getFeatures();
@ -63,9 +63,9 @@ public class NeuronTest {
@Test @Test
public void testCompareAndSetFeatures() { public void testCompareAndSetFeatures() {
final Neuron n = new Neuron(1, new double[] { 0 }); final Neuron n = new Neuron(1, new double[] {0 });
double[] expect = n.getFeatures(); double[] expect = n.getFeatures();
double[] update = new double[] { expect[0] + 1.23 }; double[] update = new double[] {expect[0] + 1.23};
// Test "success". // Test "success".
boolean ok = n.compareAndSetFeatures(expect, update); boolean ok = n.compareAndSetFeatures(expect, update);
@ -75,7 +75,7 @@ public class NeuronTest {
Assert.assertEquals(update[0], n.getFeatures()[0], 0d); Assert.assertEquals(update[0], n.getFeatures()[0], 0d);
// Test "failure". // Test "failure".
double[] update1 = new double[] { update[0] + 4.56 }; double[] update1 = new double[] {update[0] + 4.56};
// Must return "false" because the neuron has been // Must return "false" because the neuron has been
// updated: a new update can only succeed if "expect" // updated: a new update can only succeed if "expect"
// is set to the new features. // is set to the new features.
@ -88,10 +88,10 @@ public class NeuronTest {
@Test @Test
public void testCopy() { public void testCopy() {
final Neuron n = new Neuron(1, new double[] { 9.87 }); final Neuron n = new Neuron(1, new double[] {9.87 });
// Update original. // Update original.
double[] update = new double[] { n.getFeatures()[0] + 2.34 }; double[] update = new double[] {n.getFeatures()[0] + 2.34};
n.compareAndSetFeatures(n.getFeatures(), update); n.compareAndSetFeatures(n.getFeatures(), update);
// Create a copy. // Create a copy.
@ -103,7 +103,7 @@ public class NeuronTest {
copy.getNumberOfAttemptedUpdates()); copy.getNumberOfAttemptedUpdates());
// Update original. // Update original.
update = new double[] { 1.23 * n.getFeatures()[0] }; update = new double[] {1.23 * n.getFeatures()[0]};
n.compareAndSetFeatures(n.getFeatures(), update); n.compareAndSetFeatures(n.getFeatures(), update);
// Check that original and copy differ. // Check that original and copy differ.
@ -116,7 +116,7 @@ public class NeuronTest {
public void testSerialize() public void testSerialize()
throws IOException, throws IOException,
ClassNotFoundException { ClassNotFoundException {
final Neuron out = new Neuron(123, new double[] { -98.76, -1, 0, 1e-23, 543.21, 1e234 }); final Neuron out = new Neuron(123, new double[] {-98.76, -1, 0, 1e-23, 543.21, 1e234});
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(bos); final ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(out); oos.writeObject(out);

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -17,7 +17,6 @@
package org.apache.commons.math4.neuralnet; package org.apache.commons.math4.neuralnet;
/** /**
* Wraps a given initializer. * Wraps a given initializer.
*/ */

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -51,14 +51,14 @@ public class NeuronStringTest {
*/ */
@Test @Test
public void testSegmentNetwork() { public void testSegmentNetwork() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(4, false, initArray).getNetwork(); final Network net = new NeuronString(4, false, initArray).getNetwork();
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1 }) { for (long nId : new long[] {1}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -66,7 +66,7 @@ public class NeuronStringTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2 }) { for (long nId : new long[] {0, 2}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -74,7 +74,7 @@ public class NeuronStringTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 1, 3 }) { for (long nId : new long[] {1, 3}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -82,7 +82,7 @@ public class NeuronStringTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 2 }) { for (long nId : new long[] {2}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -96,14 +96,14 @@ public class NeuronStringTest {
*/ */
@Test @Test
public void testCircleNetwork() { public void testCircleNetwork() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(4, true, initArray).getNetwork(); final Network net = new NeuronString(4, true, initArray).getNetwork();
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1, 3 }) { for (long nId : new long[] {1, 3}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -111,7 +111,7 @@ public class NeuronStringTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2 }) { for (long nId : new long[] {0, 2}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -119,7 +119,7 @@ public class NeuronStringTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 1, 3 }) { for (long nId : new long[] {1, 3}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -127,7 +127,7 @@ public class NeuronStringTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 0, 2 }) { for (long nId : new long[] {0, 2}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -141,7 +141,7 @@ public class NeuronStringTest {
*/ */
@Test @Test
public void testGetNeighboursWithExclude() { public void testGetNeighboursWithExclude() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(5, true, initArray).getNetwork(); final Network net = new NeuronString(5, true, initArray).getNetwork();
final Collection<Neuron> exclude = new ArrayList<>(); final Collection<Neuron> exclude = new ArrayList<>();
exclude.add(net.getNeuron(1)); exclude.add(net.getNeuron(1));
@ -155,7 +155,7 @@ public class NeuronStringTest {
public void testSerialize() public void testSerialize()
throws IOException, throws IOException,
ClassNotFoundException { ClassNotFoundException {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronString out = new NeuronString(4, false, initArray); final NeuronString out = new NeuronString(4, false, initArray);
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream();

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -49,7 +49,7 @@ public class KohonenUpdateActionTest {
public void testUpdate() { public void testUpdate() {
final FeatureInitializer init final FeatureInitializer init
= new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, 0, 0.1)); = new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, 0, 0.1));
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final int netSize = 3; final int netSize = 3;
final Network net = new NeuronString(netSize, false, initArray).getNetwork(); final Network net = new NeuronString(netSize, false, initArray).getNetwork();
@ -67,7 +67,7 @@ public class KohonenUpdateActionTest {
// 2. when the initial neighbourhood is larger than the network's size, // 2. when the initial neighbourhood is larger than the network's size,
// all neuron's features get closer to the input's features. // all neuron's features get closer to the input's features.
final double[] features = new double[] { 0.3 }; final double[] features = new double[] {0.3};
final double[] distancesBefore = new double[netSize]; final double[] distancesBefore = new double[netSize];
int count = 0; int count = 0;
for (Neuron n : net) { for (Neuron n : net) {

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -24,23 +24,23 @@ import org.junit.Assert;
* Tests for {@link LearningFactorFunctionFactory} class. * Tests for {@link LearningFactorFunctionFactory} class.
*/ */
public class LearningFactorFunctionFactoryTest { public class LearningFactorFunctionFactoryTest {
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition0() { public void testExponentialDecayPrecondition0() {
LearningFactorFunctionFactory.exponentialDecay(0d, 0d, 2); LearningFactorFunctionFactory.exponentialDecay(0d, 0d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition1() { public void testExponentialDecayPrecondition1() {
LearningFactorFunctionFactory.exponentialDecay(1 + 1e-10, 0d, 2); LearningFactorFunctionFactory.exponentialDecay(1 + 1e-10, 0d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition2() { public void testExponentialDecayPrecondition2() {
LearningFactorFunctionFactory.exponentialDecay(1d, 0d, 2); LearningFactorFunctionFactory.exponentialDecay(1d, 0d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition3() { public void testExponentialDecayPrecondition3() {
LearningFactorFunctionFactory.exponentialDecay(1d, 1d, 100); LearningFactorFunctionFactory.exponentialDecay(1d, 1d, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition4() { public void testExponentialDecayPrecondition4() {
LearningFactorFunctionFactory.exponentialDecay(1d, 0.2, 0); LearningFactorFunctionFactory.exponentialDecay(1d, 0.2, 0);
} }
@ -58,19 +58,19 @@ public class LearningFactorFunctionFactoryTest {
Assert.assertEquals(0, f.value(Long.MAX_VALUE), 0d); Assert.assertEquals(0, f.value(Long.MAX_VALUE), 0d);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition0() { public void testQuasiSigmoidDecayPrecondition0() {
LearningFactorFunctionFactory.quasiSigmoidDecay(0d, -1d, 2); LearningFactorFunctionFactory.quasiSigmoidDecay(0d, -1d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition1() { public void testQuasiSigmoidDecayPrecondition1() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1 + 1e-10, -1d, 2); LearningFactorFunctionFactory.quasiSigmoidDecay(1 + 1e-10, -1d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition3() { public void testQuasiSigmoidDecayPrecondition3() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1d, 0d, 100); LearningFactorFunctionFactory.quasiSigmoidDecay(1d, 0d, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition4() { public void testQuasiSigmoidDecayPrecondition4() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1d, -1d, 0); LearningFactorFunctionFactory.quasiSigmoidDecay(1d, -1d, 0);
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -24,19 +24,19 @@ import org.junit.Assert;
* Tests for {@link NeighbourhoodSizeFunctionFactory} class. * Tests for {@link NeighbourhoodSizeFunctionFactory} class.
*/ */
public class NeighbourhoodSizeFunctionFactoryTest { public class NeighbourhoodSizeFunctionFactoryTest {
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition1() { public void testExponentialDecayPrecondition1() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(0, 0, 2); NeighbourhoodSizeFunctionFactory.exponentialDecay(0, 0, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition2() { public void testExponentialDecayPrecondition2() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 0, 2); NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 0, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition3() { public void testExponentialDecayPrecondition3() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 1, 100); NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 1, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition4() { public void testExponentialDecayPrecondition4() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(2, 1, 0); NeighbourhoodSizeFunctionFactory.exponentialDecay(2, 1, 0);
} }
@ -54,15 +54,15 @@ public class NeighbourhoodSizeFunctionFactoryTest {
Assert.assertEquals(0, f.value(Long.MAX_VALUE)); Assert.assertEquals(0, f.value(Long.MAX_VALUE));
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition1() { public void testQuasiSigmoidDecayPrecondition1() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(0d, -1d, 2); NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(0d, -1d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition3() { public void testQuasiSigmoidDecayPrecondition3() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, 0d, 100); NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, 0d, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition4() { public void testQuasiSigmoidDecayPrecondition4() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, -1d, 0); NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, -1d, 0);
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -24,19 +24,19 @@ import org.junit.Assert;
* Tests for {@link ExponentialDecayFunction} class * Tests for {@link ExponentialDecayFunction} class
*/ */
public class ExponentialDecayFunctionTest { public class ExponentialDecayFunctionTest {
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition1() { public void testPrecondition1() {
new ExponentialDecayFunction(0d, 0d, 2); new ExponentialDecayFunction(0d, 0d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition2() { public void testPrecondition2() {
new ExponentialDecayFunction(1d, 0d, 2); new ExponentialDecayFunction(1d, 0d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition3() { public void testPrecondition3() {
new ExponentialDecayFunction(1d, 1d, 100); new ExponentialDecayFunction(1d, 1d, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition4() { public void testPrecondition4() {
new ExponentialDecayFunction(1d, 0.2, 0); new ExponentialDecayFunction(1d, 0.2, 0);
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -24,15 +24,15 @@ import org.junit.Assert;
* Tests for {@link QuasiSigmoidDecayFunction} class * Tests for {@link QuasiSigmoidDecayFunction} class
*/ */
public class QuasiSigmoidDecayFunctionTest { public class QuasiSigmoidDecayFunctionTest {
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition1() { public void testPrecondition1() {
new QuasiSigmoidDecayFunction(0d, -1d, 2); new QuasiSigmoidDecayFunction(0d, -1d, 2);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition3() { public void testPrecondition3() {
new QuasiSigmoidDecayFunction(1d, 0d, 100); new QuasiSigmoidDecayFunction(1d, 0d, 100);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testPrecondition4() { public void testPrecondition4() {
new QuasiSigmoidDecayFunction(1d, -1d, 0); new QuasiSigmoidDecayFunction(1d, -1d, 0);
} }

View File

@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -49,9 +49,9 @@ public class NeuronSquareMesh2DTest {
private final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64); private final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
private final FeatureInitializer init = FeatureInitializerFactory.uniform(rng, 0, 2); private final FeatureInitializer init = FeatureInitializerFactory.uniform(rng, 0, 2);
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMinimalNetworkSize1() { public void testMinimalNetworkSize1() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
new NeuronSquareMesh2D(1, false, new NeuronSquareMesh2D(1, false,
2, false, 2, false,
@ -59,9 +59,9 @@ public class NeuronSquareMesh2DTest {
initArray); initArray);
} }
@Test(expected=IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testMinimalNetworkSize2() { public void testMinimalNetworkSize2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
new NeuronSquareMesh2D(2, false, new NeuronSquareMesh2D(2, false,
0, false, 0, false,
@ -71,7 +71,7 @@ public class NeuronSquareMesh2DTest {
@Test @Test
public void testGetFeaturesSize() { public void testGetFeaturesSize() {
final FeatureInitializer[] initArray = { init, init, init }; final FeatureInitializer[] initArray = {init, init, init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
@ -91,7 +91,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test2x2Network() { public void test2x2Network() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -99,9 +99,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// Neurons 0 and 3. // Neurons 0 and 3.
for (long id : new long[] { 0, 3 }) { for (long id : new long[] {0, 3 }) {
neighbours = net.getNeighbours(net.getNeuron(id)); neighbours = net.getNeighbours(net.getNeuron(id));
for (long nId : new long[] { 1, 2 }) { for (long nId : new long[] {1, 2 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -109,9 +109,9 @@ public class NeuronSquareMesh2DTest {
} }
// Neurons 1 and 2. // Neurons 1 and 2.
for (long id : new long[] { 1, 2 }) { for (long id : new long[] {1, 2 }) {
neighbours = net.getNeighbours(net.getNeuron(id)); neighbours = net.getNeighbours(net.getNeuron(id));
for (long nId : new long[] { 0, 3 }) { for (long nId : new long[] {0, 3 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -129,7 +129,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test2x2Network2() { public void test2x2Network2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -137,9 +137,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// All neurons // All neurons
for (long id : new long[] { 0, 1, 2, 3 }) { for (long id : new long[] {0, 1, 2, 3 }) {
neighbours = net.getNeighbours(net.getNeuron(id)); neighbours = net.getNeighbours(net.getNeuron(id));
for (long nId : new long[] { 0, 1, 2, 3 }) { for (long nId : new long[] {0, 1, 2, 3 }) {
if (id != nId) { if (id != nId) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
@ -157,7 +157,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x2CylinderNetwork() { public void test3x2CylinderNetwork() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -166,7 +166,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1, 2, 3 }) { for (long nId : new long[] {1, 2, 3 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -174,7 +174,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2, 4 }) { for (long nId : new long[] {0, 2, 4 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -182,7 +182,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 0, 1, 5 }) { for (long nId : new long[] {0, 1, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -190,7 +190,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 0, 4, 5 }) { for (long nId : new long[] {0, 4, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -198,7 +198,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 4. // Neuron 4.
neighbours = net.getNeighbours(net.getNeuron(4)); neighbours = net.getNeighbours(net.getNeuron(4));
for (long nId : new long[] { 1, 3, 5 }) { for (long nId : new long[] {1, 3, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -206,7 +206,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 5. // Neuron 5.
neighbours = net.getNeighbours(net.getNeuron(5)); neighbours = net.getNeighbours(net.getNeuron(5));
for (long nId : new long[] { 2, 3, 4 }) { for (long nId : new long[] {2, 3, 4 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -223,7 +223,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x2CylinderNetwork2() { public void test3x2CylinderNetwork2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false, final Network net = new NeuronSquareMesh2D(2, false,
3, true, 3, true,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -231,9 +231,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// All neurons. // All neurons.
for (long id : new long[] { 0, 1, 2, 3, 4, 5 }) { for (long id : new long[] {0, 1, 2, 3, 4, 5 }) {
neighbours = net.getNeighbours(net.getNeuron(id)); neighbours = net.getNeighbours(net.getNeuron(id));
for (long nId : new long[] { 0, 1, 2, 3, 4, 5 }) { for (long nId : new long[] {0, 1, 2, 3, 4, 5 }) {
if (id != nId) { if (id != nId) {
Assert.assertTrue("id=" + id + " nId=" + nId, Assert.assertTrue("id=" + id + " nId=" + nId,
neighbours.contains(net.getNeuron(nId))); neighbours.contains(net.getNeuron(nId)));
@ -255,7 +255,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x3TorusNetwork() { public void test3x3TorusNetwork() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, true, final Network net = new NeuronSquareMesh2D(3, true,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -264,7 +264,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1, 2, 3, 6 }) { for (long nId : new long[] {1, 2, 3, 6 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -272,7 +272,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2, 4, 7 }) { for (long nId : new long[] {0, 2, 4, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -280,7 +280,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 0, 1, 5, 8 }) { for (long nId : new long[] {0, 1, 5, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -288,7 +288,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 0, 4, 5, 6 }) { for (long nId : new long[] {0, 4, 5, 6 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -296,7 +296,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 4. // Neuron 4.
neighbours = net.getNeighbours(net.getNeuron(4)); neighbours = net.getNeighbours(net.getNeuron(4));
for (long nId : new long[] { 1, 3, 5, 7 }) { for (long nId : new long[] {1, 3, 5, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -304,7 +304,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 5. // Neuron 5.
neighbours = net.getNeighbours(net.getNeuron(5)); neighbours = net.getNeighbours(net.getNeuron(5));
for (long nId : new long[] { 2, 3, 4, 8 }) { for (long nId : new long[] {2, 3, 4, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -312,7 +312,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 6. // Neuron 6.
neighbours = net.getNeighbours(net.getNeuron(6)); neighbours = net.getNeighbours(net.getNeuron(6));
for (long nId : new long[] { 0, 3, 7, 8 }) { for (long nId : new long[] {0, 3, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -320,7 +320,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 7. // Neuron 7.
neighbours = net.getNeighbours(net.getNeuron(7)); neighbours = net.getNeighbours(net.getNeuron(7));
for (long nId : new long[] { 1, 4, 6, 8 }) { for (long nId : new long[] {1, 4, 6, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -328,7 +328,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 8. // Neuron 8.
neighbours = net.getNeighbours(net.getNeuron(8)); neighbours = net.getNeighbours(net.getNeuron(8));
for (long nId : new long[] { 2, 5, 6, 7 }) { for (long nId : new long[] {2, 5, 6, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -348,7 +348,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x3TorusNetwork2() { public void test3x3TorusNetwork2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, true, final Network net = new NeuronSquareMesh2D(3, true,
3, true, 3, true,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -356,9 +356,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours; Collection<Neuron> neighbours;
// All neurons. // All neurons.
for (long id : new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }) { for (long id : new long[] {0, 1, 2, 3, 4, 5, 6, 7, 8 }) {
neighbours = net.getNeighbours(net.getNeuron(id)); neighbours = net.getNeighbours(net.getNeuron(id));
for (long nId : new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }) { for (long nId : new long[] {0, 1, 2, 3, 4, 5, 6, 7, 8 }) {
if (id != nId) { if (id != nId) {
Assert.assertTrue("id=" + id + " nId=" + nId, Assert.assertTrue("id=" + id + " nId=" + nId,
neighbours.contains(net.getNeuron(nId))); neighbours.contains(net.getNeuron(nId)));
@ -380,7 +380,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x3CylinderNetwork() { public void test3x3CylinderNetwork() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, false, final Network net = new NeuronSquareMesh2D(3, false,
3, true, 3, true,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -389,7 +389,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1, 2, 3, 4, 5}) { for (long nId : new long[] {1, 2, 3, 4, 5}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -397,7 +397,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2, 3, 4, 5 }) { for (long nId : new long[] {0, 2, 3, 4, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -405,7 +405,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 0, 1, 3, 4, 5 }) { for (long nId : new long[] {0, 1, 3, 4, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -413,7 +413,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 0, 1, 2, 4, 5, 6, 7, 8 }) { for (long nId : new long[] {0, 1, 2, 4, 5, 6, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -421,7 +421,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 4. // Neuron 4.
neighbours = net.getNeighbours(net.getNeuron(4)); neighbours = net.getNeighbours(net.getNeuron(4));
for (long nId : new long[] { 0, 1, 2, 3, 5, 6, 7, 8 }) { for (long nId : new long[] {0, 1, 2, 3, 5, 6, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -429,7 +429,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 5. // Neuron 5.
neighbours = net.getNeighbours(net.getNeuron(5)); neighbours = net.getNeighbours(net.getNeuron(5));
for (long nId : new long[] { 0, 1, 2, 3, 4, 6, 7, 8 }) { for (long nId : new long[] {0, 1, 2, 3, 4, 6, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -437,7 +437,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 6. // Neuron 6.
neighbours = net.getNeighbours(net.getNeuron(6)); neighbours = net.getNeighbours(net.getNeuron(6));
for (long nId : new long[] { 3, 4, 5, 7, 8 }) { for (long nId : new long[] {3, 4, 5, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -445,7 +445,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 7. // Neuron 7.
neighbours = net.getNeighbours(net.getNeuron(7)); neighbours = net.getNeighbours(net.getNeuron(7));
for (long nId : new long[] { 3, 4, 5, 6, 8 }) { for (long nId : new long[] {3, 4, 5, 6, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -453,7 +453,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 8. // Neuron 8.
neighbours = net.getNeighbours(net.getNeuron(8)); neighbours = net.getNeighbours(net.getNeuron(8));
for (long nId : new long[] { 3, 4, 5, 6, 7 }) { for (long nId : new long[] {3, 4, 5, 6, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -473,7 +473,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void test3x3CylinderNetwork2() { public void test3x3CylinderNetwork2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, false, final Network net = new NeuronSquareMesh2D(3, false,
3, false, 3, false,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -482,7 +482,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 0. // Neuron 0.
neighbours = net.getNeighbours(net.getNeuron(0)); neighbours = net.getNeighbours(net.getNeuron(0));
for (long nId : new long[] { 1, 3, 4}) { for (long nId : new long[] {1, 3, 4}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -490,7 +490,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 1. // Neuron 1.
neighbours = net.getNeighbours(net.getNeuron(1)); neighbours = net.getNeighbours(net.getNeuron(1));
for (long nId : new long[] { 0, 2, 3, 4, 5 }) { for (long nId : new long[] {0, 2, 3, 4, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -498,7 +498,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 2. // Neuron 2.
neighbours = net.getNeighbours(net.getNeuron(2)); neighbours = net.getNeighbours(net.getNeuron(2));
for (long nId : new long[] { 1, 4, 5 }) { for (long nId : new long[] {1, 4, 5 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -506,7 +506,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 3. // Neuron 3.
neighbours = net.getNeighbours(net.getNeuron(3)); neighbours = net.getNeighbours(net.getNeuron(3));
for (long nId : new long[] { 0, 1, 4, 6, 7 }) { for (long nId : new long[] {0, 1, 4, 6, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -514,7 +514,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 4. // Neuron 4.
neighbours = net.getNeighbours(net.getNeuron(4)); neighbours = net.getNeighbours(net.getNeuron(4));
for (long nId : new long[] { 0, 1, 2, 3, 5, 6, 7, 8 }) { for (long nId : new long[] {0, 1, 2, 3, 5, 6, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -522,7 +522,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 5. // Neuron 5.
neighbours = net.getNeighbours(net.getNeuron(5)); neighbours = net.getNeighbours(net.getNeuron(5));
for (long nId : new long[] { 1, 2, 4, 7, 8 }) { for (long nId : new long[] {1, 2, 4, 7, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -530,7 +530,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 6. // Neuron 6.
neighbours = net.getNeighbours(net.getNeuron(6)); neighbours = net.getNeighbours(net.getNeuron(6));
for (long nId : new long[] { 3, 4, 7 }) { for (long nId : new long[] {3, 4, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -538,7 +538,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 7. // Neuron 7.
neighbours = net.getNeighbours(net.getNeuron(7)); neighbours = net.getNeighbours(net.getNeuron(7));
for (long nId : new long[] { 3, 4, 5, 6, 8 }) { for (long nId : new long[] {3, 4, 5, 6, 8 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -546,7 +546,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 8. // Neuron 8.
neighbours = net.getNeighbours(net.getNeuron(8)); neighbours = net.getNeighbours(net.getNeuron(8));
for (long nId : new long[] { 4, 5, 7 }) { for (long nId : new long[] {4, 5, 7 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -572,7 +572,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void testConcentricNeighbourhood() { public void testConcentricNeighbourhood() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(5, true, final Network net = new NeuronSquareMesh2D(5, true,
5, true, 5, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -583,7 +583,7 @@ public class NeuronSquareMesh2DTest {
// Level-1 neighbourhood. // Level-1 neighbourhood.
neighbours = net.getNeighbours(net.getNeuron(12)); neighbours = net.getNeighbours(net.getNeuron(12));
for (long nId : new long[] { 7, 11, 13, 17 }) { for (long nId : new long[] {7, 11, 13, 17 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -595,7 +595,7 @@ public class NeuronSquareMesh2DTest {
exclude.addAll(neighbours); exclude.addAll(neighbours);
// 3. Retrieve level-2 neighbourhood. // 3. Retrieve level-2 neighbourhood.
neighbours = net.getNeighbours(neighbours, exclude); neighbours = net.getNeighbours(neighbours, exclude);
for (long nId : new long[] { 6, 8, 16, 18, 2, 10, 14, 22 }) { for (long nId : new long[] {6, 8, 16, 18, 2, 10, 14, 22 }) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -621,7 +621,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void testConcentricNeighbourhood2() { public void testConcentricNeighbourhood2() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(5, true, final Network net = new NeuronSquareMesh2D(5, true,
5, true, 5, true,
SquareNeighbourhood.MOORE, SquareNeighbourhood.MOORE,
@ -632,7 +632,7 @@ public class NeuronSquareMesh2DTest {
// Level-1 neighbourhood. // Level-1 neighbourhood.
neighbours = net.getNeighbours(net.getNeuron(8)); neighbours = net.getNeighbours(net.getNeuron(8));
for (long nId : new long[] { 2, 3, 4, 7, 9, 12, 13, 14 }) { for (long nId : new long[] {2, 3, 4, 7, 9, 12, 13, 14}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -644,7 +644,7 @@ public class NeuronSquareMesh2DTest {
exclude.addAll(neighbours); exclude.addAll(neighbours);
// 3. Retrieve level-2 neighbourhood. // 3. Retrieve level-2 neighbourhood.
neighbours = net.getNeighbours(neighbours, exclude); neighbours = net.getNeighbours(neighbours, exclude);
for (long nId : new long[] { 1, 6, 11, 16, 17, 18, 19, 15, 10, 5, 0, 20, 24, 23, 22, 21 }) { for (long nId : new long[] {1, 6, 11, 16, 17, 18, 19, 15, 10, 5, 0, 20, 24, 23, 22, 21}) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
} }
// Ensures that no other neurons is in the neighbourhood set. // Ensures that no other neurons is in the neighbourhood set.
@ -655,7 +655,7 @@ public class NeuronSquareMesh2DTest {
public void testSerialize() public void testSerialize()
throws IOException, throws IOException,
ClassNotFoundException { ClassNotFoundException {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D out = new NeuronSquareMesh2D(4, false, final NeuronSquareMesh2D out = new NeuronSquareMesh2D(4, false,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -700,7 +700,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void testGetNeuron() { public void testGetNeuron() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(2, false, final NeuronSquareMesh2D net = new NeuronSquareMesh2D(2, false,
2, true, 2, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -749,7 +749,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void testGetNeuronAlongDirection() { public void testGetNeuronAlongDirection() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, false, final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, false,
3, false, 3, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -810,7 +810,7 @@ public class NeuronSquareMesh2DTest {
*/ */
@Test @Test
public void testGetNeuronAlongDirectionWrappedMap() { public void testGetNeuronAlongDirectionWrappedMap() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, true, final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, true,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -854,7 +854,7 @@ public class NeuronSquareMesh2DTest {
@Test @Test
public void testIterator() { public void testIterator() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true, final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,
@ -880,7 +880,7 @@ public class NeuronSquareMesh2DTest {
@Test @Test
public void testDataVisualization() { public void testDataVisualization() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true, final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true,
3, true, 3, true,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,

View File

@ -45,7 +45,7 @@ public class LocationFinderTest {
*/ */
@Test @Test
public void test2x2Network() { public void test2x2Network() {
final FeatureInitializer[] initArray = { init }; final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D map = new NeuronSquareMesh2D(2, false, final NeuronSquareMesh2D map = new NeuronSquareMesh2D(2, false,
2, false, 2, false,
SquareNeighbourhood.VON_NEUMANN, SquareNeighbourhood.VON_NEUMANN,

View File

@ -175,12 +175,12 @@ public class FastCosineTransform implements RealTransform {
final boolean inverse) { final boolean inverse) {
if (inverse) { if (inverse) {
return normalization == Norm.ORTHO ? return normalization == Norm.ORTHO ?
(f) -> TransformUtils.scaleInPlace(fct(f), Math.sqrt(2d / (f.length - 1))) : f -> TransformUtils.scaleInPlace(fct(f), Math.sqrt(2d / (f.length - 1))) :
(f) -> TransformUtils.scaleInPlace(fct(f), 2d / (f.length - 1)); f -> TransformUtils.scaleInPlace(fct(f), 2d / (f.length - 1));
} else { } else {
return normalization == Norm.ORTHO ? return normalization == Norm.ORTHO ?
(f) -> TransformUtils.scaleInPlace(fct(f), Math.sqrt(2d / (f.length - 1))) : f -> TransformUtils.scaleInPlace(fct(f), Math.sqrt(2d / (f.length - 1))) :
(f) -> fct(f); f -> fct(f);
} }
} }

View File

@ -135,7 +135,6 @@ public class FastFourierTransform implements ComplexTransform {
throw new TransformException(TransformException.SIZE_MISMATCH, throw new TransformException(TransformException.SIZE_MISMATCH,
dataI.length, dataR.length); dataI.length, dataR.length);
} }
final int n = dataR.length; final int n = dataR.length;
if (!ArithmeticUtils.isPowerOfTwo(n)) { if (!ArithmeticUtils.isPowerOfTwo(n)) {
throw new TransformException(TransformException.NOT_POWER_OF_TWO, throw new TransformException(TransformException.NOT_POWER_OF_TWO,
@ -236,9 +235,7 @@ public class FastFourierTransform implements ComplexTransform {
} }
// Combine even/odd transforms of size lastN0 into a transform of size N0 (lastN0 * 2). // Combine even/odd transforms of size lastN0 into a transform of size N0 (lastN0 * 2).
for (int destEvenStartIndex = 0; for (int destEvenStartIndex = 0; destEvenStartIndex < n; destEvenStartIndex += n0) {
destEvenStartIndex < n;
destEvenStartIndex += n0) {
final int destOddStartIndex = destEvenStartIndex + lastN0; final int destOddStartIndex = destEvenStartIndex + lastN0;
double wSubN0ToRR = 1; double wSubN0ToRR = 1;
@ -282,6 +279,7 @@ public class FastFourierTransform implements ComplexTransform {
* *
* @throws IllegalArgumentException if the length of the data array is not a power of two. * @throws IllegalArgumentException if the length of the data array is not a power of two.
*/ */
@Override
public Complex[] apply(final double[] f) { public Complex[] apply(final double[] f) {
final double[][] dataRI = new double[][] { final double[][] dataRI = new double[][] {
Arrays.copyOf(f, f.length), Arrays.copyOf(f, f.length),

View File

@ -308,9 +308,9 @@ public class FastHadamardTransform implements RealTransform {
*/ */
private UnaryOperator<double[]> create(final boolean inverse) { private UnaryOperator<double[]> create(final boolean inverse) {
if (inverse) { if (inverse) {
return (f) -> TransformUtils.scaleInPlace(fht(f), 1d / f.length); return f -> TransformUtils.scaleInPlace(fht(f), 1d / f.length);
} else { } else {
return (f) -> fht(f); return f -> fht(f);
} }
} }
} }

View File

@ -183,12 +183,12 @@ public class FastSineTransform implements RealTransform {
final boolean inverse) { final boolean inverse) {
if (inverse) { if (inverse) {
return normalization == Norm.ORTHO ? return normalization == Norm.ORTHO ?
(f) -> TransformUtils.scaleInPlace(fst(f), Math.sqrt(2d / f.length)) : f -> TransformUtils.scaleInPlace(fst(f), Math.sqrt(2d / f.length)) :
(f) -> TransformUtils.scaleInPlace(fst(f), 2d / f.length); f -> TransformUtils.scaleInPlace(fst(f), 2d / f.length);
} else { } else {
return normalization == Norm.ORTHO ? return normalization == Norm.ORTHO ?
(f) -> TransformUtils.scaleInPlace(fst(f), Math.sqrt(2d / f.length)) : f -> TransformUtils.scaleInPlace(fst(f), Math.sqrt(2d / f.length)) :
(f) -> fst(f); f -> fst(f);
} }
} }

View File

@ -46,7 +46,7 @@ class TransformException extends IllegalArgumentException {
* @param message Message format (with replaceable parameters). * @param message Message format (with replaceable parameters).
* @param formatArguments Actual arguments to be displayed in the message. * @param formatArguments Actual arguments to be displayed in the message.
*/ */
public TransformException(String message, Object... formatArguments) { TransformException(String message, Object... formatArguments) {
super(MessageFormat.format(message, formatArguments)); super(MessageFormat.format(message, formatArguments));
} }
} }

View File

@ -16,7 +16,6 @@
*/ */
package org.apache.commons.math4.transform; package org.apache.commons.math4.transform;
import java.util.Arrays;
import java.util.function.DoubleUnaryOperator; import java.util.function.DoubleUnaryOperator;
import org.apache.commons.numbers.complex.Complex; import org.apache.commons.numbers.complex.Complex;
@ -25,7 +24,7 @@ import org.apache.commons.numbers.complex.Complex;
* Useful functions for the implementation of various transforms. * Useful functions for the implementation of various transforms.
* Class is package-private (for internal use only). * Class is package-private (for internal use only).
*/ */
class TransformUtils { final class TransformUtils {
/** Utility class. */ /** Utility class. */
private TransformUtils() {} private TransformUtils() {}

View File

@ -71,7 +71,7 @@ public final class FastCosineTransformerTest
public static Collection<Object[]> data() { public static Collection<Object[]> data() {
final FastCosineTransform.Norm[] normalization = FastCosineTransform.Norm.values(); final FastCosineTransform.Norm[] normalization = FastCosineTransform.Norm.values();
final Object[][] data = new FastCosineTransform.Norm[normalization.length][1]; final Object[][] data = new FastCosineTransform.Norm[normalization.length][1];
for (int i = 0; i < normalization.length; i++){ for (int i = 0; i < normalization.length; i++) {
data[i][0] = normalization[i]; data[i][0] = normalization[i];
} }
return Arrays.asList(data); return Arrays.asList(data);
@ -110,7 +110,7 @@ public final class FastCosineTransformerTest
@Override @Override
DoubleUnaryOperator getValidFunction() { DoubleUnaryOperator getValidFunction() {
final UnivariateFunction sinc = new Sinc(); final UnivariateFunction sinc = new Sinc();
return (x) -> sinc.value(x); return x -> sinc.value(x);
} }
@Override @Override
@ -169,12 +169,13 @@ public final class FastCosineTransformerTest
@Test @Test
public void testAdHocData() { public void testAdHocData() {
FastCosineTransform transformer; FastCosineTransform transformer;
double result[], tolerance = 1e-12; double[] result;
double tolerance = 1e-12;
final double x[] = { final double[] x = {
0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0
}; };
final double y[] = { final double[] y = {
172.0, -105.096569476353, 27.3137084989848, -12.9593152353742, 172.0, -105.096569476353, 27.3137084989848, -12.9593152353742,
8.0, -5.78585076868676, 4.68629150101524, -4.15826451958632, 8.0, -5.78585076868676, 4.68629150101524, -4.15826451958632,
4.0 4.0
@ -211,7 +212,7 @@ public final class FastCosineTransformerTest
@Test @Test
public void testParameters() throws Exception { public void testParameters() throws Exception {
final UnivariateFunction sinFunction = new Sin(); final UnivariateFunction sinFunction = new Sin();
final DoubleUnaryOperator f = (x) -> sinFunction.value(x); final DoubleUnaryOperator f = x -> sinFunction.value(x);
final FastCosineTransform transformer = new FastCosineTransform(FastCosineTransform.Norm.STD); final FastCosineTransform transformer = new FastCosineTransform(FastCosineTransform.Norm.STD);
try { try {
@ -241,26 +242,26 @@ public final class FastCosineTransformerTest
@Test @Test
public void testSinFunction() { public void testSinFunction() {
final UnivariateFunction sinFunction = new Sin(); final UnivariateFunction sinFunction = new Sin();
final DoubleUnaryOperator f = (x) -> sinFunction.value(x); final DoubleUnaryOperator f = x -> sinFunction.value(x);
final FastCosineTransform transformer = new FastCosineTransform(FastCosineTransform.Norm.STD); final FastCosineTransform transformer = new FastCosineTransform(FastCosineTransform.Norm.STD);
double min, max, result[], tolerance = 1e-12; double tolerance = 1e-12;
int N = 9; int size = 9;
final double expected[] = { final double[] expected = {
0.0, 3.26197262739567, 0.0, -2.17958042710327, 0.0, 0.0, 3.26197262739567, 0.0, -2.17958042710327, 0.0,
-0.648846697642915, 0.0, -0.433545502649478, 0.0 -0.648846697642915, 0.0, -0.433545502649478, 0.0
}; };
min = 0.0; double min = 0.0;
max = 2.0 * Math.PI * N / (N - 1); double max = 2.0 * Math.PI * size / (size - 1);
result = transformer.apply(f, min, max, N); double[] result = transformer.apply(f, min, max, size);
for (int i = 0; i < N; i++) { for (int i = 0; i < size; i++) {
Assert.assertEquals(expected[i], result[i], tolerance); Assert.assertEquals(expected[i], result[i], tolerance);
} }
min = -Math.PI; min = -Math.PI;
max = Math.PI * (N + 1) / (N - 1); max = Math.PI * (size + 1) / (size - 1);
result = transformer.apply(f, min, max, N); result = transformer.apply(f, min, max, size);
for (int i = 0; i < N; i++) { for (int i = 0; i < size; i++) {
Assert.assertEquals(-expected[i], result[i], tolerance); Assert.assertEquals(-expected[i], result[i], tolerance);
} }
} }

View File

@ -37,7 +37,7 @@ import org.apache.commons.math3.analysis.function.Sinc;
*/ */
public final class FastFourierTransformerTest { public final class FastFourierTransformerTest {
private static final Sin SIN_FUNCTION = new Sin(); private static final Sin SIN_FUNCTION = new Sin();
private static final DoubleUnaryOperator SIN = (x) -> SIN_FUNCTION.value(x); private static final DoubleUnaryOperator SIN = x -> SIN_FUNCTION.value(x);
/** RNG. */ /** RNG. */
private static final UniformRandomProvider RNG = RandomSource.create(RandomSource.MWC_256); private static final UniformRandomProvider RNG = RandomSource.create(RandomSource.MWC_256);
@ -50,7 +50,7 @@ public final class FastFourierTransformerTest {
final Complex[] x = createComplexData(n); final Complex[] x = createComplexData(n);
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
final FastFourierTransform fft = new FastFourierTransform(norm[i], type); final FastFourierTransform fft = new FastFourierTransform(norm[i], type);
try { try {
fft.apply(x); fft.apply(x);
@ -69,7 +69,7 @@ public final class FastFourierTransformerTest {
final double[] x = createRealData(n); final double[] x = createRealData(n);
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
final FastFourierTransform fft = new FastFourierTransform(norm[i], type); final FastFourierTransform fft = new FastFourierTransform(norm[i], type);
try { try {
fft.apply(x); fft.apply(x);
@ -87,7 +87,7 @@ public final class FastFourierTransformerTest {
final int n = 127; final int n = 127;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
final FastFourierTransform fft = new FastFourierTransform(norm[i], type); final FastFourierTransform fft = new FastFourierTransform(norm[i], type);
try { try {
fft.apply(SIN, 0.0, Math.PI, n); fft.apply(SIN, 0.0, Math.PI, n);
@ -105,7 +105,7 @@ public final class FastFourierTransformerTest {
final int n = -128; final int n = -128;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
final FastFourierTransform fft = new FastFourierTransform(norm[i], type); final FastFourierTransform fft = new FastFourierTransform(norm[i], type);
try { try {
fft.apply(SIN, 0.0, Math.PI, n); fft.apply(SIN, 0.0, Math.PI, n);
@ -124,7 +124,7 @@ public final class FastFourierTransformerTest {
final int n = 128; final int n = 128;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
final FastFourierTransform fft = new FastFourierTransform(norm[i], type); final FastFourierTransform fft = new FastFourierTransform(norm[i], type);
try { try {
fft.apply(SIN, Math.PI, 0.0, n); fft.apply(SIN, Math.PI, 0.0, n);
@ -195,7 +195,7 @@ public final class FastFourierTransformerTest {
final double s; final double s;
if (!inverse) { if (!inverse) {
expected = dft(x, -1); expected = dft(x, -1);
if (normalization == FastFourierTransform.Norm.STD){ if (normalization == FastFourierTransform.Norm.STD) {
s = 1.0; s = 1.0;
} else { } else {
s = 1.0 / Math.sqrt(n); s = 1.0 / Math.sqrt(n);
@ -309,7 +309,7 @@ public final class FastFourierTransformerTest {
public void testTransformComplex() { public void testTransformComplex() {
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
doTestTransformComplex(2, 1e-15, norm[i], type); doTestTransformComplex(2, 1e-15, norm[i], type);
doTestTransformComplex(4, 1e-14, norm[i], type); doTestTransformComplex(4, 1e-14, norm[i], type);
doTestTransformComplex(8, 1e-13, norm[i], type); doTestTransformComplex(8, 1e-13, norm[i], type);
@ -325,7 +325,7 @@ public final class FastFourierTransformerTest {
public void testStandardTransformReal() { public void testStandardTransformReal() {
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
doTestTransformReal(2, 1e-15, norm[i], type); doTestTransformReal(2, 1e-15, norm[i], type);
doTestTransformReal(4, 1e-14, norm[i], type); doTestTransformReal(4, 1e-14, norm[i], type);
doTestTransformReal(8, 1e-13, norm[i], type); doTestTransformReal(8, 1e-13, norm[i], type);
@ -340,14 +340,14 @@ public final class FastFourierTransformerTest {
@Test @Test
public void testStandardTransformFunction() { public void testStandardTransformFunction() {
final UnivariateFunction sinc = new Sinc(); final UnivariateFunction sinc = new Sinc();
final DoubleUnaryOperator f = (x) -> sinc.value(x); final DoubleUnaryOperator f = x -> sinc.value(x);
final double min = -Math.PI; final double min = -Math.PI;
final double max = Math.PI; final double max = Math.PI;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values(); final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
for (int i = 0; i < norm.length; i++) { for (int i = 0; i < norm.length; i++) {
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
doTestTransformFunction(f, min, max, 2, 1e-15, norm[i], type); doTestTransformFunction(f, min, max, 2, 1e-15, norm[i], type);
doTestTransformFunction(f, min, max, 4, 1e-14, norm[i], type); doTestTransformFunction(f, min, max, 4, 1e-14, norm[i], type);
doTestTransformFunction(f, min, max, 8, 1e-14, norm[i], type); doTestTransformFunction(f, min, max, 8, 1e-14, norm[i], type);
@ -367,10 +367,11 @@ public final class FastFourierTransformerTest {
@Test @Test
public void testAdHocData() { public void testAdHocData() {
FastFourierTransform transformer; FastFourierTransform transformer;
Complex result[]; double tolerance = 1e-12; Complex[] result;
double tolerance = 1e-12;
final double x[] = {1.3, 2.4, 1.7, 4.1, 2.9, 1.7, 5.1, 2.7}; final double[] x = {1.3, 2.4, 1.7, 4.1, 2.9, 1.7, 5.1, 2.7};
final Complex y[] = { final Complex[] y = {
Complex.ofCartesian(21.9, 0.0), Complex.ofCartesian(21.9, 0.0),
Complex.ofCartesian(-2.09497474683058, 1.91507575950825), Complex.ofCartesian(-2.09497474683058, 1.91507575950825),
Complex.ofCartesian(-2.6, 2.7), Complex.ofCartesian(-2.6, 2.7),
@ -394,9 +395,9 @@ public final class FastFourierTransformerTest {
Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance);
} }
double x2[] = {10.4, 21.6, 40.8, 13.6, 23.2, 32.8, 13.6, 19.2}; double[] x2 = {10.4, 21.6, 40.8, 13.6, 23.2, 32.8, 13.6, 19.2};
TransformUtils.scaleInPlace(x2, 1.0 / Math.sqrt(x2.length)); TransformUtils.scaleInPlace(x2, 1.0 / Math.sqrt(x2.length));
Complex y2[] = y; Complex[] y2 = y;
transformer = new FastFourierTransform(FastFourierTransform.Norm.UNIT); transformer = new FastFourierTransform(FastFourierTransform.Norm.UNIT);
result = transformer.apply(y2); result = transformer.apply(y2);
@ -419,18 +420,19 @@ public final class FastFourierTransformerTest {
@Test @Test
public void testSinFunction() { public void testSinFunction() {
FastFourierTransform transformer; FastFourierTransform transformer;
Complex result[]; int N = 1 << 8; Complex[] result;
double min, max, tolerance = 1e-12; int size = 1 << 8;
double tolerance = 1e-12;
min = 0.0; double min = 0.0;
max = 2 * Math.PI; double max = 2 * Math.PI;
transformer = new FastFourierTransform(FastFourierTransform.Norm.STD); transformer = new FastFourierTransform(FastFourierTransform.Norm.STD);
result = transformer.apply(SIN, min, max, N); result = transformer.apply(SIN, min, max, size);
Assert.assertEquals(0.0, result[1].getReal(), tolerance); Assert.assertEquals(0.0, result[1].getReal(), tolerance);
Assert.assertEquals(-(N >> 1), result[1].getImaginary(), tolerance); Assert.assertEquals(-(size >> 1), result[1].getImaginary(), tolerance);
Assert.assertEquals(0.0, result[N-1].getReal(), tolerance); Assert.assertEquals(0.0, result[size - 1].getReal(), tolerance);
Assert.assertEquals(N >> 1, result[N-1].getImaginary(), tolerance); Assert.assertEquals(size >> 1, result[size - 1].getImaginary(), tolerance);
for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) { for (int i = 0; i < size - 1; i += i == 0 ? 2 : 1) {
Assert.assertEquals(0.0, result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getReal(), tolerance);
Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance);
} }
@ -438,12 +440,12 @@ public final class FastFourierTransformerTest {
min = -Math.PI; min = -Math.PI;
max = Math.PI; max = Math.PI;
transformer = new FastFourierTransform(FastFourierTransform.Norm.STD, true); transformer = new FastFourierTransform(FastFourierTransform.Norm.STD, true);
result = transformer.apply(SIN, min, max, N); result = transformer.apply(SIN, min, max, size);
Assert.assertEquals(0.0, result[1].getReal(), tolerance); Assert.assertEquals(0.0, result[1].getReal(), tolerance);
Assert.assertEquals(-0.5, result[1].getImaginary(), tolerance); Assert.assertEquals(-0.5, result[1].getImaginary(), tolerance);
Assert.assertEquals(0.0, result[N-1].getReal(), tolerance); Assert.assertEquals(0.0, result[size - 1].getReal(), tolerance);
Assert.assertEquals(0.5, result[N-1].getImaginary(), tolerance); Assert.assertEquals(0.5, result[size - 1].getImaginary(), tolerance);
for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) { for (int i = 0; i < size - 1; i += i == 0 ? 2 : 1) {
Assert.assertEquals(0.0, result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getReal(), tolerance);
Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance);
} }

View File

@ -23,7 +23,7 @@ import org.apache.commons.numbers.core.Precision;
/** /**
* Test for {@link FestHadamardTransform}. * Test for {@link FastHadamardTransform}.
*/ */
public final class FastHadamardTransformerTest { public final class FastHadamardTransformerTest {
/** /**
@ -31,8 +31,8 @@ public final class FastHadamardTransformerTest {
*/ */
@Test @Test
public void test8Points() { public void test8Points() {
checkAllTransforms(new int[] { 1, 4, -2, 3, 0, 1, 4, -1 }, checkAllTransforms(new int[] {1, 4, -2, 3, 0, 1, 4, -1},
new int[] { 10, -4, 2, -4, 2, -12, 6, 8 }); new int[] {10, -4, 2, -4, 2, -12, 6, 8});
} }
/** /**
@ -40,8 +40,8 @@ public final class FastHadamardTransformerTest {
*/ */
@Test @Test
public void test4Points() { public void test4Points() {
checkAllTransforms(new int[] { 1, 2, 3, 4 }, checkAllTransforms(new int[] {1, 2, 3, 4},
new int[] { 10, -2, -4, 0 }); new int[] {10, -2, -4, 0});
} }
/** /**
@ -50,11 +50,11 @@ public final class FastHadamardTransformerTest {
@Test @Test
public void testNoIntInverse() { public void testNoIntInverse() {
final FastHadamardTransform transformer = new FastHadamardTransform(true); final FastHadamardTransform transformer = new FastHadamardTransform(true);
final double[] x = transformer.apply(new double[] { 0, 1, 0, 1}); final double[] x = transformer.apply(new double[] {0, 1, 0, 1});
Assert.assertEquals( 0.5, x[0], 0); Assert.assertEquals(0.5, x[0], 0);
Assert.assertEquals(-0.5, x[1], 0); Assert.assertEquals(-0.5, x[1], 0);
Assert.assertEquals( 0.0, x[2], 0); Assert.assertEquals(0.0, x[2], 0);
Assert.assertEquals( 0.0, x[3], 0); Assert.assertEquals(0.0, x[3], 0);
} }
/** /**
@ -85,7 +85,7 @@ public final class FastHadamardTransformerTest {
for (int i = 0; i < dX.length; ++i) { for (int i = 0; i < dX.length; ++i) {
dX[i] = x[i]; dX[i] = x[i];
} }
final double dResult[] = transformer.apply(dX); final double[] dResult = transformer.apply(dX);
for (int i = 0; i < dResult.length; i++) { for (int i = 0; i < dResult.length; i++) {
// compare computed results to precomputed results // compare computed results to precomputed results
Assert.assertTrue(Precision.equals(y[i], dResult[i], 1)); Assert.assertTrue(Precision.equals(y[i], dResult[i], 1));
@ -97,12 +97,11 @@ public final class FastHadamardTransformerTest {
final FastHadamardTransform transformer = new FastHadamardTransform(); final FastHadamardTransform transformer = new FastHadamardTransform();
// check integer transform // check integer transform
final int iResult[] = transformer.apply(x); final int[] iResult = transformer.apply(x);
for (int i = 0; i < iResult.length; i++) { for (int i = 0; i < iResult.length; i++) {
// compare computed results to precomputed results // compare computed results to precomputed results
Assert.assertEquals(y[i], iResult[i]); Assert.assertEquals(y[i], iResult[i]);
} }
} }
private void checkInverseDoubleTransform(int[]x, int[] y) { private void checkInverseDoubleTransform(int[]x, int[] y) {
@ -114,12 +113,10 @@ public final class FastHadamardTransformerTest {
for (int i = 0; i < dY.length; ++i) { for (int i = 0; i < dY.length; ++i) {
dY[i] = y[i]; dY[i] = y[i];
} }
final double dResult[] = transformer.apply(dY); final double[] dResult = transformer.apply(dY);
for (int i = 0; i < dResult.length; i++) { for (int i = 0; i < dResult.length; i++) {
// compare computed results to precomputed results // compare computed results to precomputed results
Assert.assertTrue(Precision.equals(x[i], dResult[i], 1)); Assert.assertTrue(Precision.equals(x[i], dResult[i], 1));
} }
} }
} }

View File

@ -122,7 +122,7 @@ public final class FastSineTransformerTest extends RealTransformerAbstractTest {
@Override @Override
DoubleUnaryOperator getValidFunction() { DoubleUnaryOperator getValidFunction() {
final UnivariateFunction sinc = new Sinc(); final UnivariateFunction sinc = new Sinc();
return (x) -> sinc.value(x); return x -> sinc.value(x);
} }
@Override @Override
@ -180,7 +180,7 @@ public final class FastSineTransformerTest extends RealTransformerAbstractTest {
final double[] data = new double[] { final double[] data = new double[] {
1, 1, 1, 1 1, 1, 1, 1
}; };
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
try { try {
final RealTransform transformer = createRealTransformer(type); final RealTransform transformer = createRealTransformer(type);
transformer.apply(data); transformer.apply(data);
@ -199,19 +199,19 @@ public final class FastSineTransformerTest extends RealTransformerAbstractTest {
@Test @Test
public void testAdHocData() { public void testAdHocData() {
FastSineTransform transformer; FastSineTransform transformer;
double result[], tolerance = 1e-12; double tolerance = 1e-12;
final double x[] = { final double[] x = {
0, 1, 2, 3, 4, 5, 6, 7 0, 1, 2, 3, 4, 5, 6, 7
}; };
final double y[] = { final double[] y = {
0.0, 20.1093579685034, -9.65685424949238, 0.0, 20.1093579685034, -9.65685424949238,
5.98642305066196, -4.0, 2.67271455167720, 5.98642305066196, -4.0, 2.67271455167720,
-1.65685424949238, 0.795649469518633 -1.65685424949238, 0.795649469518633
}; };
transformer = new FastSineTransform(FastSineTransform.Norm.STD); transformer = new FastSineTransform(FastSineTransform.Norm.STD);
result = transformer.apply(x); double[] result = transformer.apply(x);
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.length; i++) {
Assert.assertEquals(y[i], result[i], tolerance); Assert.assertEquals(y[i], result[i], tolerance);
} }
@ -243,23 +243,24 @@ public final class FastSineTransformerTest extends RealTransformerAbstractTest {
@Test @Test
public void testSinFunction() { public void testSinFunction() {
final UnivariateFunction sinFunction = new Sin(); final UnivariateFunction sinFunction = new Sin();
final DoubleUnaryOperator f = (x) -> sinFunction.value(x); final DoubleUnaryOperator f = x -> sinFunction.value(x);
final FastSineTransform transformer = new FastSineTransform(FastSineTransform.Norm.STD); final FastSineTransform transformer = new FastSineTransform(FastSineTransform.Norm.STD);
double min, max, result[], tolerance = 1e-12; int N = 1 << 8; double tolerance = 1e-12;
int size = 1 << 8;
min = 0.0; double min = 0.0;
max = 2 * Math.PI; double max = 2 * Math.PI;
result = transformer.apply(f, min, max, N); double[] result = transformer.apply(f, min, max, size);
Assert.assertEquals(N >> 1, result[2], tolerance); Assert.assertEquals(size >> 1, result[2], tolerance);
for (int i = 0; i < N; i += (i == 1 ? 2 : 1)) { for (int i = 0; i < size; i += i == 1 ? 2 : 1) {
Assert.assertEquals(0.0, result[i], tolerance); Assert.assertEquals(0.0, result[i], tolerance);
} }
min = -Math.PI; min = -Math.PI;
max = Math.PI; max = Math.PI;
result = transformer.apply(f, min, max, N); result = transformer.apply(f, min, max, size);
Assert.assertEquals(-(N >> 1), result[2], tolerance); Assert.assertEquals(-(size >> 1), result[2], tolerance);
for (int i = 0; i < N; i += (i == 1 ? 2 : 1)) { for (int i = 0; i < size; i += i == 1 ? 2 : 1) {
Assert.assertEquals(0.0, result[i], tolerance); Assert.assertEquals(0.0, result[i], tolerance);
} }
} }
@ -270,7 +271,7 @@ public final class FastSineTransformerTest extends RealTransformerAbstractTest {
@Test @Test
public void testParameters() throws Exception { public void testParameters() throws Exception {
final UnivariateFunction sinFunction = new Sin(); final UnivariateFunction sinFunction = new Sin();
final DoubleUnaryOperator f = (x) -> sinFunction.value(x); final DoubleUnaryOperator f = x -> sinFunction.value(x);
final FastSineTransform transformer = new FastSineTransform(FastSineTransform.Norm.STD); final FastSineTransform transformer = new FastSineTransform(FastSineTransform.Norm.STD);
try { try {

View File

@ -20,7 +20,6 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.util.function.DoubleUnaryOperator; import java.util.function.DoubleUnaryOperator;
import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource; import org.apache.commons.rng.simple.RandomSource;
@ -29,7 +28,7 @@ import org.apache.commons.rng.simple.RandomSource;
* This abstract test handles the automatic generation of random data of various * This abstract test handles the automatic generation of random data of various
* sizes. For each generated data array, actual values (returned by the * sizes. For each generated data array, actual values (returned by the
* transformer to be tested) are compared to expected values, returned by the * transformer to be tested) are compared to expected values, returned by the
* {@link #apply(double[])} (to be implemented by the user: a naive method may * {@link #transform(double[], boolean)} (to be implemented by the user: a naive method may
* be used). Methods are also provided to test that invalid parameters throw the * be used). Methods are also provided to test that invalid parameters throw the
* expected exceptions. * expected exceptions.
* *
@ -49,7 +48,7 @@ public abstract class RealTransformerAbstractTest {
/** /**
* Returns an invalid data size. Transforms with this data size should * Returns an invalid data size. Transforms with this data size should
* trigger a {@link MathIllegalArgumentException}. * trigger a {@link IllegalArgumentException}.
* *
* @param i the index of the invalid data size ({@code 0 <= i <} * @param i the index of the invalid data size ({@code 0 <= i <}
* {@link #getNumberOfInvalidDataSizes()} * {@link #getNumberOfInvalidDataSizes()}
@ -116,7 +115,7 @@ public abstract class RealTransformerAbstractTest {
/** /**
* Returns a sampling upper bound for the accuracy check of * Returns a sampling upper bound for the accuracy check of
* {@link RealTransform#apply(DoubleUnaryOperator, double, double, int, TransformType)}. * {@link RealTransform#apply(DoubleUnaryOperator, double, double, int)}.
* This upper bound should be valid. In other words, none of the above * This upper bound should be valid. In other words, none of the above
* methods should throw an exception when passed this bound. * methods should throw an exception when passed this bound.
* *
@ -143,7 +142,7 @@ public abstract class RealTransformerAbstractTest {
public void testTransformRealInvalidDataSize() { public void testTransformRealInvalidDataSize() {
for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) { for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) {
final int n = getInvalidDataSize(i); final int n = getInvalidDataSize(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
try { try {
final RealTransform transformer = createRealTransformer(type); final RealTransform transformer = createRealTransformer(type);
transformer.apply(createRealData(n)); transformer.apply(createRealData(n));
@ -156,7 +155,7 @@ public abstract class RealTransformerAbstractTest {
} }
/** /**
* {@link RealTransformer#(DoubleUnaryOperator, double, double, int)} * {@link RealTransform#apply(DoubleUnaryOperator, double, double, int)}
* should throw {@link IllegalArgumentException} if number of samples is * should throw {@link IllegalArgumentException} if number of samples is
* invalid. * invalid.
*/ */
@ -167,7 +166,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound(); final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) { for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) {
final int n = getInvalidDataSize(i); final int n = getInvalidDataSize(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
try { try {
final RealTransform transformer = createRealTransformer(type); final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, a, b, n); transformer.apply(f, a, b, n);
@ -191,7 +190,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound(); final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfValidDataSizes(); i++) { for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i); final int n = getValidDataSize(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
try { try {
final RealTransform transformer = createRealTransformer(type); final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, a, b, -n); transformer.apply(f, a, b, -n);
@ -215,7 +214,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound(); final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfValidDataSizes(); i++) { for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i); final int n = getValidDataSize(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
try { try {
final RealTransform transformer = createRealTransformer(type); final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, b, a, n); transformer.apply(f, b, a, n);
@ -245,7 +244,7 @@ public abstract class RealTransformerAbstractTest {
for (int i = 0; i < getNumberOfValidDataSizes(); i++) { for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i); final int n = getValidDataSize(i);
final double tol = getRelativeTolerance(i); final double tol = getRelativeTolerance(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
doTestTransformReal(n, tol, type); doTestTransformReal(n, tol, type);
} }
} }
@ -253,10 +252,11 @@ public abstract class RealTransformerAbstractTest {
/** /**
* Accuracy check of * Accuracy check of
* {@link RealTransform#apply(DoubleUnaryOperator, double, double, int, TransformType)}. * {@link RealTransform#apply(DoubleUnaryOperator, double, double, int)}.
* For each valid data size returned by * For each valid data size returned by
* {@link #getValidDataSize(int) getValidDataSize(i)}, * {@link #getValidDataSize(int) getValidDataSize(i)},
* the {@link UnivariateFunction} returned by {@link #getValidFunction()} is * the {@link org.apache.commons.math3.analysis.UnivariateFunction UnivariateFunction}
* returned by {@link #getValidFunction()} is
* sampled. The actual transform is computed and compared to the expected * sampled. The actual transform is computed and compared to the expected
* transform, return by {@link #transform(double[], boolean)}. Actual * transform, return by {@link #transform(double[], boolean)}. Actual
* and expected values should be equal to within the relative error returned * and expected values should be equal to within the relative error returned
@ -267,7 +267,7 @@ public abstract class RealTransformerAbstractTest {
for (int i = 0; i < getNumberOfValidDataSizes(); i++) { for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i); final int n = getValidDataSize(i);
final double tol = getRelativeTolerance(i); final double tol = getRelativeTolerance(i);
for (boolean type : new boolean[] { true, false }) { for (boolean type : new boolean[] {true, false}) {
doTestTransformFunction(n, tol, type); doTestTransformFunction(n, tol, type);
} }
} }

View File

@ -28,20 +28,20 @@ import org.apache.commons.math3.analysis.function.Sin;
*/ */
public class TransformUtilsTest { public class TransformUtilsTest {
private static final Sin SIN_FUNCTION = new Sin(); private static final Sin SIN_FUNCTION = new Sin();
private static final DoubleUnaryOperator SIN = (x) -> SIN_FUNCTION.value(x); private static final DoubleUnaryOperator SIN = x -> SIN_FUNCTION.value(x);
@Test(expected = TransformException.class) @Test(expected = TransformException.class)
public void testSampleWrongBounds(){ public void testSampleWrongBounds() {
TransformUtils.sample(SIN, Math.PI, 0.0, 10); TransformUtils.sample(SIN, Math.PI, 0.0, 10);
} }
@Test(expected = TransformException.class) @Test(expected = TransformException.class)
public void testSampleNegativeNumberOfPoints(){ public void testSampleNegativeNumberOfPoints() {
TransformUtils.sample(SIN, 0.0, Math.PI, -1); TransformUtils.sample(SIN, 0.0, Math.PI, -1);
} }
@Test(expected = TransformException.class) @Test(expected = TransformException.class)
public void testSampleNullNumberOfPoints(){ public void testSampleNullNumberOfPoints() {
TransformUtils.sample(SIN, 0.0, Math.PI, 0); TransformUtils.sample(SIN, 0.0, Math.PI, 0);
} }

View File

@ -0,0 +1,260 @@
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Commons Numbers customization of default Checkstyle behavior:
https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/sun_checks.xml
-->
<module name="Checker">
<module name="SuppressionFilter">
<!-- Default property set by maven-checkstyle-plugin -->
<property name="file" value="${checkstyle.suppressions.file}"/>
<property name="optional" value="false"/>
</module>
<property name="localeLanguage" value="en"/>
<property name="fileExtensions" value="java, properties, xml" />
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$" />
</module>
<!-- Checks that a package-info.java file exists for each package. -->
<!-- See http://checkstyle.sourceforge.net/config_javadoc.html#JavadocPackage -->
<module name="JavadocPackage" />
<!-- Checks whether files end with a new line. -->
<!-- See http://checkstyle.sourceforge.net/config_misc.html#NewlineAtEndOfFile -->
<module name="NewlineAtEndOfFile" />
<!-- Checks that property files contain the same keys. -->
<!-- See http://checkstyle.sourceforge.net/config_misc.html#Translation -->
<module name="Translation" />
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sourceforge.net/config_sizes.html -->
<module name="FileLength" />
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<!-- Ignore lines that begin with " * ", such as within a Javadoc comment. -->
<property name="ignorePattern" value="^ *\* *[^ ]"/>
<property name="max" value="120"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sourceforge.net/config_whitespace.html -->
<module name="FileTabCharacter" />
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sourceforge.net/config_misc.html -->
<module name="RegexpSingleline">
<property name="format" value="\s+$" />
<property name="minimum" value="0" />
<property name="maximum" value="0" />
<property name="message" value="Line has trailing spaces." />
</module>
<!-- Checks for Headers -->
<!-- See http://checkstyle.sourceforge.net/config_header.html -->
<module name="Header">
<property name="headerFile" value="${checkstyle.header.file}"/>
</module>
<module name="TreeWalker">
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sourceforge.net/config_javadoc.html -->
<module name="InvalidJavadocPosition"/>
<module name="JavadocMethod" />
<module name="JavadocType" />
<module name="JavadocVariable" />
<module name="JavadocStyle" />
<!-- <module name="MissingJavadocType"/> -->
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sourceforge.net/config_naming.html -->
<module name="ConstantName" />
<module name="LocalFinalVariableName" />
<module name="LocalVariableName" />
<module name="MemberName" />
<module name="MethodName" />
<module name="PackageName" />
<module name="ParameterName" />
<module name="StaticVariableName" />
<module name="TypeName" />
<!-- Checks for imports -->
<!-- See http://checkstyle.sourceforge.net/config_import.html -->
<module name="AvoidStarImport" />
<module name="IllegalImport" /> <!-- defaults to sun.* packages -->
<module name="RedundantImport" />
<module name="UnusedImports">
<property name="processJavadoc" value="false" />
</module>
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sourceforge.net/config_sizes.html -->
<module name="MethodLength" />
<module name="ParameterNumber" />
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sourceforge.net/config_whitespace.html -->
<module name="EmptyForIteratorPad" />
<module name="GenericWhitespace" />
<module name="MethodParamPad" />
<module name="NoWhitespaceAfter" />
<module name="NoWhitespaceBefore" />
<!-- Operator must be at end of wrapped line -->
<module name="OperatorWrap">
<property name="option" value="eol"/>
</module>
<module name="ParenPad" />
<module name="TypecastParenPad" />
<module name="WhitespaceAfter">
<property name="tokens" value="COMMA, SEMI, LITERAL_IF, LITERAL_ELSE, LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, DO_WHILE"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyTypes" value="true"/>
</module>
<!-- Modifier Checks -->
<!-- See http://checkstyle.sourceforge.net/config_modifiers.html -->
<module name="ModifierOrder" />
<module name="RedundantModifier" />
<!-- Checks for blocks. You know, those {}'s -->
<!-- See http://checkstyle.sourceforge.net/config_blocks.html -->
<module name="AvoidNestedBlocks" />
<module name="EmptyBlock" />
<module name="LeftCurly" />
<module name="NeedBraces" />
<module name="RightCurly" />
<!-- Checks for common coding problems -->
<!-- See http://checkstyle.sourceforge.net/config_coding.html -->
<module name="EmptyStatement" />
<module name="EqualsHashCode" />
<!-- Method parameters and local variables should not hide fields, except in constructors and setters -->
<module name="HiddenField">
<property name="ignoreConstructorParameter" value="true" />
<property name="ignoreSetter" value="true" />
</module>
<!-- Disallow unnecessary instantiation of Boolean, String -->
<module name="IllegalInstantiation">
<property name="classes" value="java.lang.Boolean, java.lang.String"/>
</module>
<!-- Allowed for algorithm implementations. -->
<!-- <module name="InnerAssignment" /> -->
<!-- <module name="MagicNumber" /> -->
<module name="MissingSwitchDefault" />
<module name="MultipleVariableDeclarations" />
<module name="SimplifyBooleanExpression" />
<module name="SimplifyBooleanReturn" />
<!-- Checks for class design -->
<!-- See http://checkstyle.sourceforge.net/config_design.html -->
<module name="DesignForExtension" />
<module name="FinalClass" />
<module name="HideUtilityClassConstructor" />
<module name="InterfaceIsType" />
<!-- No public fields -->
<module name="VisibilityModifier">
<property name="protectedAllowed" value="true"/>
</module>
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sourceforge.net/config_misc.html -->
<module name="ArrayTypeStyle" />
<!-- <module name="FinalParameters" /> -->
<module name="TodoComment">
<property name="severity" value="warning"/>
</module>
<module name="UpperEll" />
<!-- Addition to Checkstyle sun_checks.xml -->
<!-- Indentation of 4 spaces. -->
<module name="Indentation">
<!-- Indentation style recommended by Oracle -->
<property name="caseIndent" value="0"/>
</module>
<!-- Switch statements should have independent cases -->
<module name="FallThrough" />
<!-- Constant names should obey the traditional all uppercase naming convention -->
<module name="ConstantName" />
<!-- No System.out.println() statements -->
<module name="Regexp">
<!-- no sysouts -->
<property name="format" value="System\.(out|err)\."/>
<property name="illegalPattern" value="true"/>
</module>
<!-- Authors should be in pom.xml file -->
<module name="Regexp">
<property name="format" value="@author"/>
<property name="illegalPattern" value="true"/>
<property name="message" value="Developers names should be in pom file"/>
</module>
<!-- Use a consistent way to put declarations -->
<module name="DeclarationOrder" />
<!-- Don't add up parentheses when they are not required -->
<module name="UnnecessaryParentheses" />
<!-- Don't use too widespread catch (Exception, Throwable, RuntimeException) -->
<module name="IllegalCatch" />
<!-- Don't use = or != for string comparisons -->
<module name="StringLiteralEquality" />
<!-- String literals more than one character long should not be repeated several times -->
<!-- the "unchecked" string is also accepted to allow @SuppressWarnings("unchecked") -->
<module name="MultipleStringLiterals" >
<property name="ignoreStringsRegexp" value='^(("")|(".")|("unchecked"))$'/>
</module>
<!-- Check if @Override tags are present -->
<module name="MissingOverride" />
<!-- Setup special comments to suppress specific checks from source files -->
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE\: stop ([\w\|]+)"/>
<property name="onCommentFormat" value="CHECKSTYLE\: resume ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE\: stop all"/>
<property name="onCommentFormat" value="CHECKSTYLE\: resume all"/>
</module>
</module>
</module>

View File

@ -0,0 +1,26 @@
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<!-- Disable all checks for main code! XXX -->
<suppress checks=".*" files=".*[/\\]main[/\\].*" />
<!-- Disable all checks for unit tests. -->
<suppress checks=".*" files=".*[/\\]test[/\\].*" />
</suppressions>

View File

@ -19,8 +19,32 @@
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd"> "https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions> <suppressions>
<!-- Disable all checks for main code! XXX --> <suppress checks="HiddenField" files=".*[/\\]examples[/\\]sofm[/\\]tsp[/\\]City\.java" />
<suppress checks=".*" files=".*[/\\]main[/\\].*" /> <suppress checks="LineLength" files=".*[/\\]LocalizedFormats\.java" />
<!-- Disable all checks for unit tests. --> <suppress checks="FileLength" files=".*[/\\]AccurateMath.*\.java" />
<suppress checks=".*" files=".*[/\\]test[/\\].*" /> <suppress checks="FileLength" files=".*[/\\]Dfp.*\.java" />
<suppress checks="UnnecessaryParentheses" files=".*[/\\]AccurateMath.*\.java" />
<suppress checks="UnnecessaryParentheses" files=".*[/\\]Dfp.*\.java" />
<suppress checks="LineLength" files=".*[/\\]AccurateMath\.java" />
<suppress checks="LineLength" files=".*[/\\]Dfp\.java" />
<suppress checks="MethodLength" files=".*[/\\]Dfp.*\.java" />
<suppress checks="MethodLength" files=".*[/\\]AccurateMath\.java" />
<suppress checks="MethodName" files=".*[/\\]AccurateMath\.java" />
<suppress checks="LocalFinalVariableName" files=".*[/\\]AccurateMath\.java" />
<suppress checks="ParameterNumber" files=".*[/\\]RealFieldElement\.java" />
<suppress checks="ParameterNumber" files=".*[/\\]Dfp\.java" />
<suppress checks="TypeName" files=".*[/\\]AccurateMath\.java" />
<suppress checks="ParameterName" files=".*[/\\]AccurateMathCalc\.java" />
<!-- Be more lenient on tests. -->
<suppress checks="Javadoc" files=".*[/\\]test[/\\].*" />
<suppress checks="MultipleStringLiterals" files=".*[/\\]test[/\\].*" />
<suppress checks="DesignForExtension" files=".*[/\\]test[/\\].*" />
<suppress checks="LineLength" files=".*[/\\]test[/\\].*" />
<suppress checks="IllegalCatch" files=".*[/\\]test[/\\].*" />
<suppress checks="MethodName" files=".*[/\\]test[/\\].*" />
<suppress checks="ConstantName" files=".*[/\\]test[/\\].*" />
<suppress checks="MethodLength" files=".*/Dfp.*Test.java" />
<suppress checks="MethodLength" files=".*[/\\]AccurateMathTest\.java" />
<suppress checks="LocalFinalVariableName" files=".*[/\\]AccurateMathTest\.java" />
</suppressions> </suppressions>

View File

@ -81,6 +81,7 @@
<!-- See http://checkstyle.sourceforge.net/config_header.html --> <!-- See http://checkstyle.sourceforge.net/config_header.html -->
<module name="Header"> <module name="Header">
<property name="headerFile" value="${checkstyle.header.file}"/> <property name="headerFile" value="${checkstyle.header.file}"/>
<property name="fileExtensions" value="java"/>
</module> </module>
<module name="TreeWalker"> <module name="TreeWalker">