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

@ -45,7 +45,7 @@ class ChineseRings {
* @param numPointsRing1 Number of points in the first ring.
* @param numPointsRing2 Number of points in the second ring.
*/
public ChineseRings(Vector3D orientationRing1,
ChineseRings(Vector3D orientationRing1,
double radiusRing1,
double halfWidthRing1,
double radiusRing2,
@ -113,6 +113,8 @@ class ChineseRings {
/**
* Gets all the points.
*
* @return the points
*/
public Vector3D[] getPoints() {
return points.clone();
@ -125,24 +127,28 @@ class ChineseRings {
*/
public Iterable<double[]> createIterable() {
return new Iterable<double[]>() {
@Override
public Iterator<double[]> iterator() {
return new Iterator<double[]>() {
/** Data. */
final Vector3D[] points = getPoints();
private final Vector3D[] points = getPoints();
/** Number of samples. */
private int n = 0;
/** {@inheritDoc} */
@Override
public boolean hasNext() {
return n < points.length;
}
/** {@inheritDoc} */
@Override
public double[] next() {
return points[n++].toArray();
}
/** {@inheritDoc} */
@Override
public void remove() {
throw new UnsupportedOperationException();
}

View File

@ -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.FeatureInitializer;
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.EuclideanDistance;
import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
@ -54,7 +53,7 @@ class ChineseRingsClassifier {
* @param dim1 Number of rows of the SOFM.
* @param dim2 Number of columns of the SOFM.
*/
public ChineseRingsClassifier(ChineseRings rings,
ChineseRingsClassifier(ChineseRings rings,
int dim1,
int dim2) {
this.rings = rings;
@ -164,24 +163,27 @@ class ChineseRingsClassifier {
private Iterator<double[]> createRandomIterator(final long numSamples) {
return new Iterator<double[]>() {
/** Data. */
final Vector3D[] points = rings.getPoints();
private final Vector3D[] points = rings.getPoints();
/** RNG. */
final UniformRandomProvider rng = RandomSource.create(RandomSource.KISS);
private final UniformRandomProvider rng = RandomSource.create(RandomSource.KISS);
/** Number of samples. */
private long n = 0;
/** {@inheritDoc} */
@Override
public boolean hasNext() {
return n < numSamples;
}
/** {@inheritDoc} */
@Override
public double[] next() {
++n;
return points[rng.nextInt(points.length)].toArray();
}
/** {@inheritDoc} */
@Override
public void remove() {
throw new UnsupportedOperationException();
}

View File

@ -35,19 +35,23 @@ import org.apache.commons.math4.neuralnet.twod.NeuronSquareMesh2D;
*/
@Command(description = "Run the application",
mixinStandardHelpOptions = true)
public class StandAlone implements Callable<Void> {
public final class StandAlone implements Callable<Void> {
/** The number of rows. */
@Option(names = { "-r" }, paramLabel = "numRows",
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",
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",
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,
description = "Output file name.")
private String _outputFile = null;
private String outputFile = null;
/**
* Program entry point.
@ -65,9 +69,9 @@ public class StandAlone implements Callable<Void> {
20, 1,
2000, 1500);
final ChineseRingsClassifier classifier = new ChineseRingsClassifier(rings, _numRows, _numCols);
classifier.createSequentialTask(_numSamples).run();
printResult(_outputFile, classifier);
final ChineseRingsClassifier classifier = new ChineseRingsClassifier(rings, numRows, numCols);
classifier.createSequentialTask(numSamples).run();
printResult(outputFile, classifier);
return null;
}
@ -81,10 +85,11 @@ public class StandAlone implements Callable<Void> {
* @throws FileNotFoundException If the file cannot be created.
*/
private static void printResult(String fileName,
ChineseRingsClassifier sofm) throws FileNotFoundException, UnsupportedEncodingException {
ChineseRingsClassifier sofm)
throws FileNotFoundException, UnsupportedEncodingException {
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("# Quantization error: " + result.getMeanQuantizationError());
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;
import org.apache.commons.rng.simple.RandomSource;
/**
* Application class.
*/
public class StandAlone {
public final class StandAlone {
/** No instances. */
private StandAlone() {}
/**
* 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

@ -26,11 +26,11 @@ import java.util.HashSet;
*/
public class City {
/** Identifier. */
final String name;
private final String name;
/** x-coordinate. */
final double x;
private final double x;
/** y-coordinate. */
final double y;
private final double y;
/**
* @param name Name.
@ -56,7 +56,7 @@ public class City {
* @return the (x, y) coordinates.
*/
public double[] getCoordinates() {
return new double[] { x, y };
return new double[] {x, y};
}
/**
@ -116,7 +116,7 @@ public class City {
++count;
}
return new double[] { xB / count, yB / count };
return new double[] {xB / count, yB / count};
}
/**

View File

@ -35,22 +35,27 @@ import org.apache.commons.rng.simple.RandomSource;
*/
@Command(description = "Run the application",
mixinStandardHelpOptions = true)
public class StandAlone implements Callable<Void> {
public final class StandAlone implements Callable<Void> {
/** The neurons per city. */
@Option(names = { "-n" }, paramLabel = "neuronsPerCity",
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",
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",
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",
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,
description = "Output file name.")
private String _outputFile = null;
private String outputFile = null;
/**
* Program entry point.
@ -62,7 +67,7 @@ public class StandAlone implements Callable<Void> {
}
@Override
public Void call() throws Exception {
public Void call() throws FileNotFoundException, UnsupportedEncodingException {
// Cities (in optimal travel order).
final City[] cities = new City[] {
new City("o0", 0, 0),
@ -87,11 +92,11 @@ public class StandAlone implements Callable<Void> {
double minDist = Double.POSITIVE_INFINITY;
int count = 0;
while (count++ < _maxTrials) {
while (count++ < maxTrials) {
final City[] travel = TravellingSalesmanSolver.solve(cities,
_neuronsPerCity,
_numSamples,
_numJobs,
neuronsPerCity,
numSamples,
numJobs,
rng);
final int numCities = City.unique(travel).size();
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;
}
@ -146,8 +151,9 @@ public class StandAlone implements Callable<Void> {
*/
private static void printSummary(String fileName,
City[] travel,
double optimalDistance) throws FileNotFoundException, UnsupportedEncodingException {
try (final PrintWriter out = new PrintWriter(fileName, StandardCharsets.UTF_8.name())) {
double optimalDistance)
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("# Travel distance: " + computeDistance(travel));
out.println("# Optimal travel distance: " + optimalDistance);

View File

@ -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
* 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;
/** SOFM. */
private final Network net;
@ -121,7 +122,7 @@ public class TravellingSalesmanSolver {
for (Future<?> f : execOutput) {
f.get();
}
} catch (InterruptedException|ExecutionException e) {
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
// Terminate all threads.
@ -172,7 +173,7 @@ public class TravellingSalesmanSolver {
* in random order.
*
* @param numSamples Number of samples.
* @param cities Cities.
* @param uniqueCities Cities.
* @param random RNG.
* @return the iterator.
*/
@ -300,13 +301,13 @@ public class TravellingSalesmanSolver {
*/
class HarmonicOscillator implements DoubleUnaryOperator {
/** Amplitude. */
final double amplitude;
private final double amplitude;
/** Angular speed. */
final double omega;
private final double omega;
/** Phase. */
final double phase;
private final double phase;
/** Offset. */
final double offset;
private final double offset;
/**
* @param amplitude Amplitude.
@ -314,7 +315,7 @@ class HarmonicOscillator implements DoubleUnaryOperator {
* @param phase Phase.
* @param offset Offset (ordinate).
*/
public HarmonicOscillator(double amplitude,
HarmonicOscillator(double amplitude,
double omega,
double phase,
double offset) {

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();
/** Compute n &times; this. Multiplication by an integer number is defined
* as the following sum
* <center>
* n &times; this = &sum;<sub>i=1</sub><sup>n</sup> this.
* </center>
* as the following sum:
* <p>n &times; this = &sum;<sub>i=1</sub><sup>n</sup> this.
* @param n Number of times {@code this} must be added to itself.
* @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
*/
public class IntegerSequence {
public final class IntegerSequence {
/**
* Utility class contains only static methods.
*/
@ -128,7 +128,7 @@ public class IntegerSequence {
* custom {@link MaxCountExceededCallback callback}, in order to e.g.
* select which exception must be thrown.
*/
public static class Incrementor implements Iterator<Integer> {
public static final class Incrementor implements Iterator<Integer> {
/** Default callback. */
private static final MaxCountExceededCallback CALLBACK
= new MaxCountExceededCallback() {

View File

@ -18,12 +18,8 @@
package org.apache.commons.math4.legacy.core;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.apache.commons.numbers.core.Precision;
@ -46,7 +42,7 @@ import org.apache.commons.math4.legacy.core.jdkmath.AccurateMath;
*
* @since 3.0
*/
public class MathArrays {
public final class MathArrays {
/**
* Private constructor.
@ -570,7 +566,7 @@ public class MathArrays {
* @since 3.4
*/
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])) {
throw new NotANumberException();
}
@ -600,7 +596,7 @@ public class MathArrays {
* @since 3.1
*/
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++) {
if (in[i][j] < 0) {
throw new NotPositiveException(in[i][j]);
@ -620,7 +616,7 @@ public class MathArrays {
* and equal elements.
*/
public static boolean equals(float[] x, float[] y) {
if ((x == null) || (y == null)) {
if (x == null || y == null) {
return !((x == null) ^ (y == null));
}
if (x.length != y.length) {
@ -646,7 +642,7 @@ public class MathArrays {
* @since 2.2
*/
public static boolean equalsIncludingNaN(float[] x, float[] y) {
if ((x == null) || (y == null)) {
if (x == null || y == null) {
return !((x == null) ^ (y == null));
}
if (x.length != y.length) {
@ -671,7 +667,7 @@ public class MathArrays {
* dimension and equal elements.
*/
public static boolean equals(double[] x, double[] y) {
if ((x == null) || (y == null)) {
if (x == null || y == null) {
return !((x == null) ^ (y == null));
}
if (x.length != y.length) {
@ -697,7 +693,7 @@ public class MathArrays {
* @since 2.2
*/
public static boolean equalsIncludingNaN(double[] x, double[] y) {
if ((x == null) || (y == null)) {
if (x == null || y == null) {
return !((x == null) ^ (y == null));
}
if (x.length != y.length) {
@ -1049,10 +1045,12 @@ public class MathArrays {
throw new MathIllegalArgumentException(LocalizedFormats.NAN_ELEMENT_AT_INDEX, Integer.valueOf(i));
}
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) {
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) {
containsPositiveWeight = true;
@ -1077,7 +1075,7 @@ public class MathArrays {
* @throws NullPointerException if any of the arrays are null
* @since 3.6
*/
public static double[] concatenate(double[] ...x) {
public static double[] concatenate(double[]... x) {
int combinedLength = 0;
for (double[] a : x) {
combinedLength += a.length;

View File

@ -87,7 +87,8 @@ public interface RealFieldElement<T> extends FieldElement<T> {
*/
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
*/
T rint();
@ -405,7 +406,7 @@ public interface RealFieldElement<T> extends FieldElement<T> {
* @param e2 second element
* @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;
}
@ -415,7 +416,7 @@ public interface RealFieldElement<T> extends FieldElement<T> {
* @param e2 second element
* @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;
}
}

View File

@ -103,10 +103,10 @@ public class Dfp implements RealFieldElement<Dfp> {
public static final int MIN_EXP = -32767;
/** The maximum exponent before overflow is signaled and results flushed
* to infinity */
* to infinity. */
public static final int MAX_EXP = 32768;
/** The amount under/overflows are scaled by before going to trap handler */
/** The amount under/overflows are scaled by before going to trap handler. */
public static final int ERR_SCALE = 32760;
/** Indicator value for normal finite numbers. */
@ -279,7 +279,7 @@ public class Dfp implements RealFieldElement<Dfp> {
exponent++;
// Normalize the subnormal number
while ( (mantissa & 0x0010000000000000L) == 0) {
while ((mantissa & 0x0010000000000000L) == 0) {
exponent--;
mantissa <<= 1;
}
@ -302,7 +302,7 @@ public class Dfp implements RealFieldElement<Dfp> {
}
Dfp xdfp = new Dfp(field, mantissa);
xdfp = xdfp.divide(new Dfp(field, 4503599627370496l)).add(field.getOne()); // Divide by 2^52, then add one
xdfp = xdfp.divide(new Dfp(field, 4503599627370496L)).add(field.getOne()); // Divide by 2^52, then add one
xdfp = xdfp.multiply(DfpMath.pow(field.getTwo(), exponent));
if ((bits & 0x8000000000000000L) != 0) {
@ -313,7 +313,6 @@ public class Dfp implements RealFieldElement<Dfp> {
sign = xdfp.sign;
exp = xdfp.exp;
nans = xdfp.nans;
}
/** Copy constructor.
@ -375,13 +374,11 @@ public class Dfp implements RealFieldElement<Dfp> {
if (p != -1) {
// scientific notation
fpdecimal = s.substring(0, p);
String fpexp = s.substring(p+1);
String fpexp = s.substring(p + 1);
boolean negative = false;
for (int i=0; i<fpexp.length(); i++)
{
if (fpexp.charAt(i) == '-')
{
for (int i = 0; i < fpexp.length(); i++) {
if (fpexp.charAt(i) == '-') {
negative = true;
continue;
}
@ -434,14 +431,14 @@ public class Dfp implements RealFieldElement<Dfp> {
striped[1] = '0';
striped[2] = '0';
striped[3] = '0';
int significantDigits=0;
for(;;) {
int significantDigits = 0;
for (;;) {
if (p == (fpdecimal.length())) {
break;
}
// Don't want to run pass the end of the array
if (q == mant.length*rsize+offset+1) {
if (q == mant.length * rsize + offset + 1) {
break;
}
@ -486,12 +483,12 @@ public class Dfp implements RealFieldElement<Dfp> {
// Implicit decimal point at end of number if not present
if (!decimalFound) {
decimalPos = q-offset;
decimalPos = q - offset;
}
// Find the number of significant trailing zeros
q = offset; // set q to point to first sig digit
p = significantDigits-1+offset;
p = significantDigits - 1 + offset;
while (p > q) {
if (striped[p] != '0') {
@ -516,20 +513,19 @@ public class Dfp implements RealFieldElement<Dfp> {
// and where the least significant digit is
for (i = mant.length - 1; i >= 0; i--) {
mant[i] = (striped[q] - '0') * 1000 +
(striped[q+1] - '0') * 100 +
(striped[q+2] - '0') * 10 +
(striped[q+3] - '0');
(striped[q + 1] - '0') * 100 +
(striped[q + 2] - '0') * 10 +
(striped[q + 3] - '0');
q += 4;
}
exp = (decimalPos+sciexp) / rsize;
exp = (decimalPos + sciexp) / rsize;
if (q < striped.length) {
// Is there possible another digit?
round((striped[q] - '0')*1000);
round((striped[q] - '0') * 1000);
}
}
/** Creates an instance with a non-finite value.
@ -602,7 +598,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return new Dfp(d);
}
/** Create an instance from a String representation.
@ -624,7 +619,8 @@ public class Dfp implements RealFieldElement<Dfp> {
return field.newDfp(sig, code);
}
/** Get the {@link org.apache.commons.math4.legacy.core.Field Field} (really a {@link DfpField}) to which the instance belongs.
/** Get the {@link org.apache.commons.math4.legacy.core.Field Field} (really a
* {@link DfpField}) to which the instance belongs.
* <p>
* The field is linked to the number of digits and acts as a factory
* for {@link Dfp} instances.
@ -668,7 +664,7 @@ public class Dfp implements RealFieldElement<Dfp> {
*/
protected void shiftLeft() {
for (int i = mant.length - 1; i > 0; i--) {
mant[i] = mant[i-1];
mant[i] = mant[i - 1];
}
mant[0] = 0;
exp--;
@ -680,7 +676,7 @@ public class Dfp implements RealFieldElement<Dfp> {
*/
protected void shiftRight() {
for (int i = 0; i < mant.length - 1; i++) {
mant[i] = mant[i+1];
mant[i] = mant[i + 1];
}
mant[mant.length - 1] = 0;
exp++;
@ -744,7 +740,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return lostdigit;
}
/** Check if instance is less than x.
@ -809,7 +804,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return (sign < 0) || ((mant[mant.length - 1] == 0) && !isInfinite());
}
/** Check if instance is strictly less than 0.
@ -824,7 +818,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return (sign < 0) && ((mant[mant.length - 1] != 0) || isInfinite());
}
/** Check if instance is greater than or equal to 0.
@ -839,7 +832,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return (sign > 0) || ((mant[mant.length - 1] == 0) && !isInfinite());
}
/** Check if instance is strictly greater than 0.
@ -854,7 +846,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return (sign > 0) && ((mant[mant.length - 1] != 0) || isInfinite());
}
/** Get the absolute value of instance.
@ -894,7 +885,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return (mant[mant.length - 1] == 0) && !isInfinite();
}
/** Check if instance is equal to x.
@ -914,7 +904,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return false;
}
/**
@ -941,7 +930,7 @@ public class Dfp implements RealFieldElement<Dfp> {
/** Compare two instances.
* @param a first instance in comparison
* @param b second instance in comparison
* @return -1 if a<b, 1 if a>b and 0 if a==b
* @return -1 if {@code a < b}, 1 if {@code a > b} and 0 if {@code a == b}
* Note this method does not properly handle NaNs or numbers with different precision.
*/
private static int compare(final Dfp a, final Dfp b) {
@ -973,7 +962,7 @@ public class Dfp implements RealFieldElement<Dfp> {
}
// Handle special case when a or b is zero, by ignoring the exponents
if (b.mant[b.mant.length-1] != 0 && a.mant[b.mant.length-1] != 0) {
if (b.mant[b.mant.length - 1] != 0 && a.mant[b.mant.length - 1] != 0) {
if (a.exp < b.exp) {
return -a.sign;
}
@ -995,7 +984,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return 0;
}
/** Round to nearest integer using the round-half-even method.
@ -1040,12 +1028,11 @@ public class Dfp implements RealFieldElement<Dfp> {
final Dfp result = this.subtract(this.divide(d).rint().multiply(d));
// IEEE 854-1987 says that if the result is zero, then it carries the sign of this
if (result.mant[mant.length-1] == 0) {
if (result.mant[mant.length - 1] == 0) {
result.sign = sign;
}
return result;
}
/** Does the integer conversions with the specified rounding.
@ -1063,7 +1050,7 @@ public class Dfp implements RealFieldElement<Dfp> {
return newInstance(this);
}
if (mant[mant.length-1] == 0) {
if (mant[mant.length - 1] == 0) {
// a is zero
return newInstance(this);
}
@ -1089,7 +1076,7 @@ public class Dfp implements RealFieldElement<Dfp> {
* a with the fractional part lopped off. */
Dfp result = newInstance(this);
for (int i = 0; i < mant.length-result.exp; i++) {
for (int i = 0; i < mant.length - result.exp; i++) {
changed |= result.mant[i] != 0;
result.mant[i] = 0;
}
@ -1122,7 +1109,7 @@ public class Dfp implements RealFieldElement<Dfp> {
}
/* If exactly equal to 1/2 and odd then increment */
if (a.equals(half) && result.exp > 0 && (result.mant[mant.length-result.exp]&1) != 0) {
if (a.equals(half) && result.exp > 0 && (result.mant[mant.length - result.exp] & 1) != 0) {
a = newInstance(getOne());
a.sign = sign;
result = result.add(a);
@ -1191,13 +1178,13 @@ public class Dfp implements RealFieldElement<Dfp> {
* @since 3.2
*/
public int intLog10() {
if (mant[mant.length-1] > 1000) {
if (mant[mant.length - 1] > 1000) {
return exp * 4 - 1;
}
if (mant[mant.length-1] > 100) {
if (mant[mant.length - 1] > 100) {
return exp * 4 - 2;
}
if (mant[mant.length-1] > 10) {
if (mant[mant.length - 1] > 10) {
return exp * 4 - 3;
}
return exp * 4 - 4;
@ -1240,9 +1227,9 @@ public class Dfp implements RealFieldElement<Dfp> {
*/
protected int complement(int extra) {
extra = RADIX-extra;
extra = RADIX - extra;
for (int i = 0; i < mant.length; i++) {
mant[i] = RADIX-mant[i]-1;
mant[i] = RADIX - mant[i] - 1;
}
int rh = extra / RADIX;
@ -1322,14 +1309,16 @@ public class Dfp implements RealFieldElement<Dfp> {
rsign = asign;
}
/* Handle special case when a or b is zero, by setting the exponent
of the zero number equal to the other one. This avoids an alignment
which would cause catastropic loss of precision */
if (b.mant[mant.length-1] == 0) {
/*
* Handle special case when a or b is zero, by setting the exponent of the zero
* number equal to the other one. This avoids an alignment which would cause
* catastropic loss of precision
*/
if (b.mant[mant.length - 1] == 0) {
b.exp = a.exp;
}
if (a.mant[mant.length-1] == 0) {
if (a.mant[mant.length - 1] == 0) {
a.exp = b.exp;
}
@ -1354,7 +1343,7 @@ public class Dfp implements RealFieldElement<Dfp> {
/* add the mantissas */
int rh = 0; /* acts as a carry */
for (int i = 0; i < mant.length; i++) {
final int r = a.mant[i]+b.mant[i]+rh;
final int r = a.mant[i] + b.mant[i] + rh;
rh = r / RADIX;
result.mant[i] = r - rh * RADIX;
}
@ -1367,7 +1356,7 @@ public class Dfp implements RealFieldElement<Dfp> {
if (rh != 0 && (asign == bsign)) {
final int lostdigit = result.mant[0];
result.shiftRight();
result.mant[mant.length-1] = rh;
result.mant[mant.length - 1] = rh;
final int excp = result.round(lostdigit);
if (excp != 0) {
result = dotrap(excp, ADD_TRAP, x, result);
@ -1376,19 +1365,19 @@ public class Dfp implements RealFieldElement<Dfp> {
/* normalize the result */
for (int i = 0; i < mant.length; i++) {
if (result.mant[mant.length-1] != 0) {
if (result.mant[mant.length - 1] != 0) {
break;
}
result.shiftLeft();
if (i == 0) {
result.mant[0] = aextradigit+bextradigit;
result.mant[0] = aextradigit + bextradigit;
aextradigit = 0;
bextradigit = 0;
}
}
/* result is zero if after normalization the most sig. digit is zero */
if (result.mant[mant.length-1] == 0) {
if (result.mant[mant.length - 1] == 0) {
result.exp = 0;
if (asign != bsign) {
@ -1412,7 +1401,7 @@ public class Dfp implements RealFieldElement<Dfp> {
@Override
public Dfp negate() {
Dfp result = newInstance(this);
result.sign = (byte) - result.sign;
result.sign = (byte) -result.sign;
return result;
}
@ -1477,7 +1466,7 @@ public class Dfp implements RealFieldElement<Dfp> {
if (rh != 0) {
shiftRight();
mant[mant.length-1] = rh;
mant[mant.length - 1] = rh;
}
}
@ -1531,13 +1520,13 @@ public class Dfp implements RealFieldElement<Dfp> {
return x;
}
if (nans == INFINITE && x.nans == FINITE && x.mant[mant.length-1] != 0) {
if (nans == INFINITE && x.nans == FINITE && x.mant[mant.length - 1] != 0) {
result = newInstance(this);
result.sign = (byte) (sign * x.sign);
return result;
}
if (x.nans == INFINITE && nans == FINITE && mant[mant.length-1] != 0) {
if (x.nans == INFINITE && nans == FINITE && mant[mant.length - 1] != 0) {
result = newInstance(x);
result.sign = (byte) (sign * x.sign);
return result;
@ -1549,8 +1538,8 @@ public class Dfp implements RealFieldElement<Dfp> {
return result;
}
if ( (x.nans == INFINITE && nans == FINITE && mant[mant.length-1] == 0) ||
(nans == INFINITE && x.nans == FINITE && x.mant[mant.length-1] == 0) ) {
if ((x.nans == INFINITE && nans == FINITE && mant[mant.length - 1] == 0) ||
(nans == INFINITE && x.nans == FINITE && x.mant[mant.length - 1] == 0)) {
field.setIEEEFlagsBits(DfpField.FLAG_INVALID);
result = newInstance(getZero());
result.nans = QNAN;
@ -1559,18 +1548,18 @@ public class Dfp implements RealFieldElement<Dfp> {
}
}
int[] product = new int[mant.length*2]; // Big enough to hold even the largest result
int[] product = new int[mant.length * 2]; // Big enough to hold even the largest result
for (int i = 0; i < mant.length; i++) {
int rh = 0; // acts as a carry
for (int j=0; j<mant.length; j++) {
for (int j = 0; j < mant.length; j++) {
int r = mant[i] * x.mant[j]; // multiply the 2 digits
r += product[i+j] + rh; // add to the product digit with carry in
r += product[i + j] + rh; // add to the product digit with carry in
rh = r / RADIX;
product[i+j] = r - rh * RADIX;
product[i + j] = r - rh * RADIX;
}
product[i+mant.length] = rh;
product[i + mant.length] = rh;
}
// Find the most sig digit
@ -1589,16 +1578,16 @@ public class Dfp implements RealFieldElement<Dfp> {
// Fixup the exponent.
result.exp = exp + x.exp + md - 2 * mant.length + 1;
result.sign = (byte)((sign == x.sign)?1:-1);
result.sign = (byte) ((sign == x.sign) ? 1 : -1);
if (result.mant[mant.length-1] == 0) {
if (result.mant[mant.length - 1] == 0) {
// if result is zero, set exp to zero
result.exp = 0;
}
final int excp;
if (md > (mant.length-1)) {
excp = result.round(product[md-mant.length]);
if (md > (mant.length - 1)) {
excp = result.round(product[md - mant.length]);
} else {
excp = result.round(0); // has no effect except to check status
}
@ -1672,10 +1661,10 @@ public class Dfp implements RealFieldElement<Dfp> {
if (rh != 0) {
lostdigit = result.mant[0];
result.shiftRight();
result.mant[mant.length-1] = rh;
result.mant[mant.length - 1] = rh;
}
if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero
if (result.mant[mant.length - 1] == 0) { // if result is zero, set exp to zero
result.exp = 0;
}
@ -1693,15 +1682,15 @@ public class Dfp implements RealFieldElement<Dfp> {
*/
@Override
public Dfp divide(Dfp divisor) {
int dividend[]; // current status of the dividend
int quotient[]; // quotient
int remainder[];// remainder
int[] dividend; // current status of the dividend
int[] quotient; // quotient
int[] remainder; // remainder
int qd; // current quotient digit we're working with
int nsqd; // number of significant quotient digits we have
int trial=0; // trial quotient digit
int trial = 0; // trial quotient digit
int minadj; // minimum adjustment
boolean trialgood; // Flag to indicate a good trail digit
int md=0; // most sig digit in result
int md = 0; // most sig digit in result
int excp; // exceptions
// make sure we don't mix number with different precision
@ -1746,7 +1735,7 @@ public class Dfp implements RealFieldElement<Dfp> {
}
/* Test for divide by zero */
if (divisor.mant[mant.length-1] == 0) {
if (divisor.mant[mant.length - 1] == 0) {
field.setIEEEFlagsBits(DfpField.FLAG_DIV_ZERO);
result = newInstance(getZero());
result.sign = (byte) (sign * divisor.sign);
@ -1755,19 +1744,18 @@ public class Dfp implements RealFieldElement<Dfp> {
return result;
}
dividend = new int[mant.length+1]; // one extra digit needed
quotient = new int[mant.length+2]; // two extra digits needed 1 for overflow, 1 for rounding
remainder = new int[mant.length+1]; // one extra digit needed
dividend = new int[mant.length + 1]; // one extra digit needed
quotient = new int[mant.length + 2]; // two extra digits needed 1 for overflow, 1 for rounding
remainder = new int[mant.length + 1]; // one extra digit needed
/* Initialize our most significant digits to zero */
dividend[mant.length] = 0;
quotient[mant.length] = 0;
quotient[mant.length+1] = 0;
quotient[mant.length + 1] = 0;
remainder[mant.length] = 0;
/* copy our mantissa into the dividend, initialize the
quotient while we are at it */
/* copy our mantissa into the dividend, initialize the quotient while we are at it */
for (int i = 0; i < mant.length; i++) {
dividend[i] = mant[i];
@ -1777,23 +1765,23 @@ public class Dfp implements RealFieldElement<Dfp> {
/* outer loop. Once per quotient digit */
nsqd = 0;
for (qd = mant.length+1; qd >= 0; qd--) {
for (qd = mant.length + 1; qd >= 0; qd--) {
/* Determine outer limits of our quotient digit */
// r = most sig 2 digits of dividend
final int divMsb = dividend[mant.length]*RADIX+dividend[mant.length-1];
int min = divMsb / (divisor.mant[mant.length-1]+1);
int max = (divMsb + 1) / divisor.mant[mant.length-1];
final int divMsb = dividend[mant.length] * RADIX + dividend[mant.length - 1];
int min = divMsb / (divisor.mant[mant.length - 1] + 1);
int max = (divMsb + 1) / divisor.mant[mant.length - 1];
trialgood = false;
while (!trialgood) {
// try the mean
trial = (min+max)/2;
trial = (min + max) / 2;
/* Multiply by divisor and store as remainder */
int rh = 0;
for (int i = 0; i < mant.length + 1; i++) {
int dm = (i<mant.length)?divisor.mant[i]:0;
int dm = (i < mant.length) ? divisor.mant[i] : 0;
final int r = (dm * trial) + rh;
rh = r / RADIX;
remainder[i] = r - rh * RADIX;
@ -1802,7 +1790,7 @@ public class Dfp implements RealFieldElement<Dfp> {
/* subtract the remainder from the dividend */
rh = 1; // carry in to aid the subtraction
for (int i = 0; i < mant.length + 1; i++) {
final int r = ((RADIX-1) - remainder[i]) + dividend[i] + rh;
final int r = ((RADIX - 1) - remainder[i]) + dividend[i] + rh;
rh = r / RADIX;
remainder[i] = r - rh * RADIX;
}
@ -1810,21 +1798,21 @@ public class Dfp implements RealFieldElement<Dfp> {
/* Lets analyze what we have here */
if (rh == 0) {
// trial is too big -- negative remainder
max = trial-1;
max = trial - 1;
continue;
}
/* find out how far off the remainder is telling us we are */
minadj = (remainder[mant.length] * RADIX)+remainder[mant.length-1];
minadj /= divisor.mant[mant.length-1] + 1;
minadj = (remainder[mant.length] * RADIX) + remainder[mant.length - 1];
minadj /= divisor.mant[mant.length - 1] + 1;
if (minadj >= 2) {
min = trial+minadj; // update the minimum
min = trial + minadj; // update the minimum
continue;
}
/* May have a good one here, check more thoroughly. Basically
its a good one if it is less than the divisor */
/* May have a good one here, check more thoroughly. Basically its a good
* one if it is less than the divisor */
trialgood = false; // assume false
for (int i = mant.length - 1; i >= 0; i--) {
if (divisor.mant[i] > remainder[i]) {
@ -1840,8 +1828,8 @@ public class Dfp implements RealFieldElement<Dfp> {
trialgood = false;
}
if (trialgood == false) {
min = trial+1;
if (!trialgood) {
min = trial + 1;
}
}
@ -1878,20 +1866,20 @@ public class Dfp implements RealFieldElement<Dfp> {
}
/* Copy the digits into the result */
for (int i=0; i<mant.length; i++) {
result.mant[mant.length-i-1] = quotient[md-i];
for (int i = 0; i < mant.length; i++) {
result.mant[mant.length - i - 1] = quotient[md - i];
}
/* Fixup the exponent. */
result.exp = exp - divisor.exp + md - mant.length;
result.sign = (byte) ((sign == divisor.sign) ? 1 : -1);
if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero
if (result.mant[mant.length - 1] == 0) { // if result is zero, set exp to zero
result.exp = 0;
}
if (md > (mant.length-1)) {
excp = result.round(quotient[md-mant.length]);
if (md > (mant.length - 1)) {
excp = result.round(quotient[md - mant.length]);
} else {
excp = result.round(0);
}
@ -1943,14 +1931,14 @@ public class Dfp implements RealFieldElement<Dfp> {
Dfp result = newInstance(this);
int rl = 0;
for (int i = mant.length-1; i >= 0; i--) {
final int r = rl*RADIX + result.mant[i];
for (int i = mant.length - 1; i >= 0; i--) {
final int r = rl * RADIX + result.mant[i];
final int rh = r / divisor;
rl = r - rh * divisor;
result.mant[i] = rh;
}
if (result.mant[mant.length-1] == 0) {
if (result.mant[mant.length - 1] == 0) {
// normalize
result.shiftLeft();
final int r = rl * RADIX; // compute the next digit and put it in
@ -1982,7 +1970,7 @@ public class Dfp implements RealFieldElement<Dfp> {
public Dfp sqrt() {
// check for unusual cases
if (nans == FINITE && mant[mant.length-1] == 0) {
if (nans == FINITE && mant[mant.length - 1] == 0) {
// if zero
return newInstance(this);
}
@ -2026,18 +2014,18 @@ public class Dfp implements RealFieldElement<Dfp> {
}
/* Coarsely estimate the mantissa */
switch (x.mant[mant.length-1] / 2000) {
switch (x.mant[mant.length - 1] / 2000) {
case 0:
x.mant[mant.length-1] = x.mant[mant.length-1]/2+1;
x.mant[mant.length - 1] = x.mant[mant.length - 1] / 2 + 1;
break;
case 2:
x.mant[mant.length-1] = 1500;
x.mant[mant.length - 1] = 1500;
break;
case 3:
x.mant[mant.length-1] = 2200;
x.mant[mant.length - 1] = 2200;
break;
default:
x.mant[mant.length-1] = 3000;
x.mant[mant.length - 1] = 3000;
}
Dfp dx = newInstance(x);
@ -2063,7 +2051,7 @@ public class Dfp implements RealFieldElement<Dfp> {
// if dx is zero, break. Note testing the most sig digit
// is a sufficient test since dx is normalized
if (dx.mant[mant.length-1] == 0) {
if (dx.mant[mant.length - 1] == 0) {
break;
}
}
@ -2098,8 +2086,8 @@ public class Dfp implements RealFieldElement<Dfp> {
* @return string representation of the instance in scientific notation
*/
protected String dfp2sci() {
char rawdigits[] = new char[mant.length * 4];
char outputbuffer[] = new char[mant.length * 4 + 20];
char[] rawdigits = new char[mant.length * 4];
char[] outputbuffer = new char[mant.length * 4 + 20];
int p;
int q;
int e;
@ -2110,7 +2098,7 @@ public class Dfp implements RealFieldElement<Dfp> {
p = 0;
for (int i = mant.length - 1; i >= 0; i--) {
rawdigits[p++] = (char) ((mant[i] / 1000) + '0');
rawdigits[p++] = (char) (((mant[i] / 100) %10) + '0');
rawdigits[p++] = (char) (((mant[i] / 100) % 10) + '0');
rawdigits[p++] = (char) (((mant[i] / 10) % 10) + '0');
rawdigits[p++] = (char) (((mant[i]) % 10) + '0');
}
@ -2134,7 +2122,7 @@ public class Dfp implements RealFieldElement<Dfp> {
outputbuffer[q++] = rawdigits[p++];
outputbuffer[q++] = '.';
while (p<rawdigits.length) {
while (p < rawdigits.length) {
outputbuffer[q++] = rawdigits[p++];
}
} else {
@ -2143,7 +2131,7 @@ public class Dfp implements RealFieldElement<Dfp> {
outputbuffer[q++] = '0';
outputbuffer[q++] = 'e';
outputbuffer[q++] = '0';
return new String(outputbuffer, 0, 5);
return String.valueOf(outputbuffer, 0, 5);
}
outputbuffer[q++] = 'e';
@ -2157,8 +2145,9 @@ public class Dfp implements RealFieldElement<Dfp> {
}
// Find the largest p such that p < e
for (p = 1000000000; p > ae; p /= 10) {
// nothing to do
p = 1000000000;
while (p > ae) {
p /= 10;
}
if (e < 0) {
@ -2171,15 +2160,14 @@ public class Dfp implements RealFieldElement<Dfp> {
p /= 10;
}
return new String(outputbuffer, 0, q);
return String.valueOf(outputbuffer, 0, q);
}
/** Convert an instance to a string using normal notation.
* @return string representation of the instance in normal notation
*/
protected String dfp2string() {
char buffer[] = new char[mant.length*4 + 20];
char[] buffer = new char[mant.length * 4 + 20];
int p = 1;
int q;
int e = exp;
@ -2235,7 +2223,7 @@ public class Dfp implements RealFieldElement<Dfp> {
}
// Suppress trailing zeros
while (buffer[p-1] == '0') {
while (buffer[p - 1] == '0') {
p--;
}
@ -2244,8 +2232,7 @@ public class Dfp implements RealFieldElement<Dfp> {
buffer[--q] = '-';
}
return new String(buffer, q, p - q);
return String.valueOf(buffer, q, p - q);
}
/** Raises a trap. This does not set the corresponding flag however.
@ -2266,14 +2253,14 @@ public class Dfp implements RealFieldElement<Dfp> {
break;
case DfpField.FLAG_DIV_ZERO:
if (nans == FINITE && mant[mant.length-1] != 0) {
if (nans == FINITE && mant[mant.length - 1] != 0) {
// normal case, we are finite, non-zero
def = newInstance(getZero());
def.sign = (byte)(sign*oper.sign);
def.sign = (byte) (sign * oper.sign);
def.nans = INFINITE;
}
if (nans == FINITE && mant[mant.length-1] == 0) {
if (nans == FINITE && mant[mant.length - 1] == 0) {
// 0/0
def = newInstance(getZero());
def.nans = QNAN;
@ -2291,7 +2278,7 @@ public class Dfp implements RealFieldElement<Dfp> {
break;
case DfpField.FLAG_UNDERFLOW:
if ( (result.exp+mant.length) < MIN_EXP) {
if ((result.exp + mant.length) < MIN_EXP) {
def = newInstance(getZero());
def.sign = result.sign;
} else {
@ -2381,11 +2368,11 @@ public class Dfp implements RealFieldElement<Dfp> {
Dfp result;
if (up) {
inc = newInstance(getOne());
inc.exp = this.exp-mant.length+1;
inc.exp = this.exp - mant.length + 1;
inc.sign = this.sign;
if (this.equals(getZero())) {
inc.exp = MIN_EXP-mant.length;
inc.exp = MIN_EXP - mant.length;
}
result = add(inc);
@ -2395,13 +2382,13 @@ public class Dfp implements RealFieldElement<Dfp> {
inc.sign = this.sign;
if (this.equals(inc)) {
inc.exp = this.exp-mant.length;
inc.exp = this.exp - mant.length;
} else {
inc.exp = this.exp-mant.length+1;
inc.exp = this.exp - mant.length + 1;
}
if (this.equals(getZero())) {
inc.exp = MIN_EXP-mant.length;
inc.exp = MIN_EXP - mant.length;
}
result = this.subtract(inc);
@ -2412,13 +2399,12 @@ public class Dfp implements RealFieldElement<Dfp> {
result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result);
}
if (result.equals(getZero()) && this.equals(getZero()) == false) {
if (result.equals(getZero()) && !this.equals(getZero())) {
field.setIEEEFlagsBits(DfpField.FLAG_INEXACT);
result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result);
}
return result;
}
/** Convert the instance into a double.
@ -2479,9 +2465,9 @@ public class Dfp implements RealFieldElement<Dfp> {
}
y = y.multiply(newInstance(4503599627370496l)).rint();
y = y.multiply(newInstance(4503599627370496L)).rint();
String str = y.toString();
str = str.substring(0, str.length()-1);
str = str.substring(0, str.length() - 1);
long mantissa = Long.parseLong(str);
if (mantissa == 4503599627370496L) {
@ -2508,7 +2494,6 @@ public class Dfp implements RealFieldElement<Dfp> {
}
return x;
}
/** Convert the instance into a split double.
@ -2516,7 +2501,7 @@ public class Dfp implements RealFieldElement<Dfp> {
* @see #toDouble()
*/
public double[] toSplitDouble() {
double split[] = new double[2];
double[] split = new double[2];
long mask = 0xffffffffc0000000L;
split[0] = Double.longBitsToDouble(Double.doubleToLongBits(toDouble()) & mask);

View File

@ -163,7 +163,7 @@ public class DfpDec extends Dfp {
@Override
protected int round(int in) {
int msb = mant[mant.length-1];
int msb = mant[mant.length - 1];
if (msb == 0) {
// special case -- this == zero
return 0;
@ -173,7 +173,7 @@ public class DfpDec extends Dfp {
int lsbthreshold = 1000;
while (lsbthreshold > msb) {
lsbthreshold /= 10;
cmaxdigits --;
cmaxdigits--;
}
@ -196,12 +196,12 @@ public class DfpDec extends Dfp {
final int n;
if (lsbthreshold == 1) {
// look to the next digit for rounding
n = (mant[lsd-1] / 1000) % 10;
mant[lsd-1] %= 1000;
discarded |= mant[lsd-1];
n = (mant[lsd - 1] / 1000) % 10;
mant[lsd - 1] %= 1000;
discarded |= mant[lsd - 1];
} else {
n = (lsb * 10 / lsbthreshold) % 10;
discarded |= lsb % (lsbthreshold/10);
discarded |= lsb % (lsbthreshold / 10);
}
for (int i = 0; i < lsd; i++) {
@ -262,7 +262,7 @@ public class DfpDec extends Dfp {
if (rh != 0) {
shiftRight();
mant[mant.length-1]=rh;
mant[mant.length - 1] = rh;
}
}
@ -323,7 +323,7 @@ public class DfpDec extends Dfp {
inc = copysign(inc, this);
if (this.equals(getZero())) {
inc = power10K(MIN_EXP-mant.length-1);
inc = power10K(MIN_EXP - mant.length - 1);
}
if (inc.equals(getZero())) {
@ -342,7 +342,7 @@ public class DfpDec extends Dfp {
}
if (this.equals(getZero())) {
inc = power10K(MIN_EXP-mant.length-1);
inc = power10K(MIN_EXP - mant.length - 1);
}
if (inc.equals(getZero())) {
@ -357,7 +357,7 @@ public class DfpDec extends Dfp {
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);
result = dotrap(DfpField.FLAG_INEXACT, trapName, x, result);
}

View File

@ -529,7 +529,7 @@ public class DfpField implements Field<Dfp> {
* @return an array of two {@link Dfp Dfp} instances which sum equals a
*/
private Dfp[] split(final String a) {
Dfp result[] = new Dfp[2];
Dfp[] result = new Dfp[2];
boolean leading = true;
int sp = 0;
int sig = 0;
@ -554,11 +554,11 @@ public class DfpField implements Field<Dfp> {
}
if (buf[i] >= '0' && buf[i] <= '9' && !leading) {
sig ++;
sig++;
}
}
result[0] = new Dfp(this, new String(buf, 0, sp));
result[0] = new Dfp(this, String.valueOf(buf, 0, sp));
for (int i = 0; i < buf.length; i++) {
buf[i] = a.charAt(i);
@ -567,10 +567,9 @@ public class DfpField implements Field<Dfp> {
}
}
result[1] = new Dfp(this, new String(buf));
result[1] = new Dfp(this, String.valueOf(buf));
return result;
}
/** 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}
* @since 2.2
*/
public class DfpMath {
public final class DfpMath {
/** Name for traps triggered by 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
*/
protected static Dfp[] split(final DfpField field, final String a) {
Dfp result[] = new Dfp[2];
Dfp[] result = new Dfp[2];
char[] buf;
boolean leading = true;
int sp = 0;
@ -68,11 +68,11 @@ public class DfpMath {
}
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++) {
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;
}
@ -199,7 +199,6 @@ public class DfpMath {
}
return result[0];
}
/** Raises base to the power a by successive squaring.
@ -207,8 +206,7 @@ public class DfpMath {
* @param a power
* @return base<sup>a</sup>
*/
public static Dfp pow(Dfp base, int a)
{
public static Dfp pow(Dfp base, int a) {
boolean invert = false;
Dfp result = base.getOne();
@ -235,7 +233,7 @@ public class DfpMath {
prevtrial = trial;
r = r.multiply(r);
trial *= 2;
} while (a>trial);
} while (a > trial);
r = prevr;
trial = prevtrial;
@ -250,7 +248,6 @@ public class DfpMath {
}
return base.newInstance(result);
}
/** 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
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();
spy = splitMult(a.getField().getLn2Split(), spx);
spz[0] = spz[0].add(spy[0]);
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();
spy = splitMult(a.getField().getLn5Split(), spx);
@ -374,7 +371,6 @@ public class DfpMath {
spz[1] = spz[1].add(spy[1]);
return a.newInstance(spz[0].add(spz[1]));
}
/** 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
* @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
* 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
* @return sin(a)
*/
protected static Dfp sinInternal(Dfp a[]) {
protected static Dfp sinInternal(Dfp[] a) {
Dfp c = a[0].add(a[1]);
Dfp y = c;
@ -682,7 +678,7 @@ public class DfpMath {
x = x.multiply(c);
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));
if (y.equals(py)) {
break;
@ -699,7 +695,7 @@ public class DfpMath {
* @param a number from which cosine is desired, in split form
* @return cos(a)
*/
protected static Dfp cosInternal(Dfp a[]) {
protected static Dfp cosInternal(Dfp[] a) {
final Dfp one = a[0].getOne();
@ -759,7 +755,7 @@ public class DfpMath {
if (x.lessThan(pi.divide(4))) {
y = sinInternal(split(x));
} else {
final Dfp c[] = new Dfp[2];
final Dfp[] c = new Dfp[2];
final Dfp[] piSplit = a.getField().getPiSplit();
c[0] = piSplit[0].divide(2).subtract(x);
c[1] = piSplit[1].divide(2);
@ -803,13 +799,13 @@ public class DfpMath {
Dfp y;
if (x.lessThan(pi.divide(4))) {
Dfp c[] = new Dfp[2];
Dfp[] c = new Dfp[2];
c[0] = x;
c[1] = zero;
y = cosInternal(c);
} else {
final Dfp c[] = new Dfp[2];
final Dfp[] c = new Dfp[2];
final Dfp[] piSplit = a.getField().getPiSplit();
c[0] = piSplit[0].divide(2).subtract(x);
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
*
@ -893,7 +889,7 @@ public class DfpMath {
}
if (x.greaterThan(ty)) {
Dfp sty[] = new Dfp[2];
Dfp[] sty = new Dfp[2];
sub = true;
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.
* @since 3.0
*/
class AccurateMathCalc {
final class AccurateMathCalc {
/**
* 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
/** 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, // 1
@ -57,7 +57,7 @@ class AccurateMathCalc {
};
/** Coefficients for slowLog. */
private static final double LN_SPLIT_COEF[][] = {
private static final double[][] LN_SPLIT_COEF = {
{2.0, 0.0},
{0.6666666269302368, 3.9736429850260626E-8},
{0.3999999761581421, 2.3841857910019882E-8},
@ -101,7 +101,7 @@ class AccurateMathCalc {
private static void buildSinCosTables(double[] SINE_TABLE_A, double[] SINE_TABLE_B,
double[] COSINE_TABLE_A, double[] COSINE_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 */
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 */
for (int i = 7; i < SINE_TABLE_LEN; i++) {
double xs[] = new double[2];
double ys[] = new double[2];
double as[] = new double[2];
double bs[] = new double[2];
double temps[] = new double[2];
double[] xs = new double[2];
double[] ys = new double[2];
double[] as = new double[2];
double[] bs = new double[2];
double[] temps = new double[2];
if ( (i & 1) == 0) {
if ((i & 1) == 0) {
// Even, use double angle
xs[0] = SINE_TABLE_A[i/2];
xs[1] = SINE_TABLE_B[i/2];
ys[0] = COSINE_TABLE_A[i/2];
ys[1] = COSINE_TABLE_B[i/2];
xs[0] = SINE_TABLE_A[i / 2];
xs[1] = SINE_TABLE_B[i / 2];
ys[0] = COSINE_TABLE_A[i / 2];
ys[1] = COSINE_TABLE_B[i / 2];
/* compute sine */
splitMult(xs, ys, result);
@ -145,14 +145,14 @@ class AccurateMathCalc {
COSINE_TABLE_A[i] = result[0];
COSINE_TABLE_B[i] = result[1];
} else {
xs[0] = SINE_TABLE_A[i/2];
xs[1] = SINE_TABLE_B[i/2];
ys[0] = COSINE_TABLE_A[i/2];
ys[1] = COSINE_TABLE_B[i/2];
as[0] = SINE_TABLE_A[i/2+1];
as[1] = SINE_TABLE_B[i/2+1];
bs[0] = COSINE_TABLE_A[i/2+1];
bs[1] = COSINE_TABLE_B[i/2+1];
xs[0] = SINE_TABLE_A[i / 2];
xs[1] = SINE_TABLE_B[i / 2];
ys[0] = COSINE_TABLE_A[i / 2];
ys[1] = COSINE_TABLE_B[i / 2];
as[0] = SINE_TABLE_A[i / 2 + 1];
as[1] = SINE_TABLE_B[i / 2 + 1];
bs[0] = COSINE_TABLE_A[i / 2 + 1];
bs[1] = COSINE_TABLE_B[i / 2 + 1];
/* compute sine */
splitMult(xs, bs, temps);
@ -174,9 +174,9 @@ class AccurateMathCalc {
/* Compute tangent = sine/cosine */
for (int i = 0; i < SINE_TABLE_LEN; i++) {
double xs[] = new double[2];
double ys[] = new double[2];
double as[] = new double[2];
double[] xs = new double[2];
double[] ys = new double[2];
double[] as = new double[2];
as[0] = COSINE_TABLE_A[i];
as[1] = COSINE_TABLE_B[i];
@ -191,7 +191,6 @@ class AccurateMathCalc {
TANGENT_TABLE_A[i] = as[0];
TANGENT_TABLE_B[i] = as[1];
}
}
/**
@ -202,27 +201,28 @@ class AccurateMathCalc {
* (may be null)
* @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 ys[] = new double[2];
final double facts[] = new double[2];
final double as[] = new double[2];
final double[] xs = new double[2];
final double[] ys = new double[2];
final double[] facts = new double[2];
final double[] as = new double[2];
split(x, xs);
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);
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;
}
split(FACT[i], as);
splitReciprocal(as, facts);
if ( (i & 2) != 0 ) { // alternate terms are negative
if ((i & 2) != 0) { // alternate terms are negative
facts[0] = -facts[0];
facts[1] = -facts[1];
}
@ -247,26 +247,27 @@ class AccurateMathCalc {
* (may be null)
* @return sin(x)
*/
static double slowSin(final double x, final double result[]) {
final double xs[] = new double[2];
final double ys[] = new double[2];
final double facts[] = new double[2];
final double as[] = new double[2];
static double slowSin(final double x, final double[] result) {
final double[] xs = new double[2];
final double[] ys = new double[2];
final double[] facts = new double[2];
final double[] as = new double[2];
split(x, xs);
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);
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;
}
split(FACT[i], as);
splitReciprocal(as, facts);
if ( (i & 2) != 0 ) { // alternate terms are negative
if ((i & 2) != 0) { // alternate terms are negative
facts[0] = -facts[0];
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 result placeholder where to place exp(x) split in two terms
* for extra precision (i.e. exp(x) = result[0] + result[1]
* @return exp(x)
*/
static double slowexp(final double x, final double result[]) {
final double xs[] = new double[2];
final double ys[] = new double[2];
final double facts[] = new double[2];
final double as[] = new double[2];
static double slowexp(final double x, final double[] result) {
final double[] xs = new double[2];
final double[] ys = new double[2];
final double[] facts = new double[2];
final double[] as = new double[2];
split(x, xs);
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);
ys[0] = as[0];
ys[1] = as[1];
@ -325,7 +326,7 @@ class AccurateMathCalc {
* @param d number to split
* @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) {
final double a = d * HEX_40000000;
split[0] = (d + a) - a;
@ -341,7 +342,7 @@ class AccurateMathCalc {
* @param a input/out array containing the split, changed
* 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 d = -(c - a[0] - a[1]);
@ -361,7 +362,7 @@ class AccurateMathCalc {
* @param b second term of multiplication
* @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[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 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[1] = a[1] + b[1];
@ -399,8 +400,8 @@ class AccurateMathCalc {
* @param in initial number, in split form
* @param result placeholder where to put the result
*/
static void splitReciprocal(final double in[], final double result[]) {
final double b = 1.0/4194304.0;
static void splitReciprocal(final double[] in, final double[] result) {
final double b = 1.0 / 4194304.0;
final double a = 1.0 - b;
if (in[0] == 0.0) {
@ -409,7 +410,7 @@ class AccurateMathCalc {
}
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
result[1] = 0.0;
@ -434,10 +435,10 @@ class AccurateMathCalc {
* @param b second term of the multiplication
* @param result placeholder where to put the result
*/
private static void quadMult(final double a[], final double b[], final double result[]) {
final double xs[] = new double[2];
final double ys[] = new double[2];
final double zs[] = new double[2];
private static void quadMult(final double[] a, final double[] b, final double[] result) {
final double[] xs = new double[2];
final double[] ys = new double[2];
final double[] zs = new double[2];
/* a[0] * b[0] */
split(a[0], xs);
@ -488,11 +489,11 @@ class AccurateMathCalc {
* @param result placeholder where to put the result in extended precision
* @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;
final double xs[] = new double[2];
final double as[] = new double[2];
final double ys[] = new double[2];
final double[] xs = new double[2];
final double[] as = new double[2];
final double[] ys = new double[2];
//split(x, xs);
//xs[1] = (double)(2.7182818284590452353602874713526625L - xs[0]);
//xs[0] = 2.71827697753906250000;
@ -547,10 +548,10 @@ class AccurateMathCalc {
* @return log(xi)
*/
static double[] slowLog(double xi) {
double x[] = new double[2];
double x2[] = new double[2];
double y[] = new double[2];
double a[] = new double[2];
double[] x = new double[2];
double[] x2 = new double[2];
double[] y = new double[2];
double[] a = new double[2];
split(xi, x);
@ -571,10 +572,10 @@ class AccurateMathCalc {
//x[0] -= 1.0;
//resplit(x);
y[0] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][0];
y[1] = LN_SPLIT_COEF[LN_SPLIT_COEF.length-1][1];
y[0] = LN_SPLIT_COEF[LN_SPLIT_COEF.length - 1][0];
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);
y[0] = a[0];
y[1] = a[1];
@ -603,9 +604,9 @@ class AccurateMathCalc {
checkLen(expectedLen, array2d.length);
out.println(TABLE_START_DECL + " ");
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(" {");
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.println("}, // " + i++);
@ -624,7 +625,7 @@ class AccurateMathCalc {
out.println(name + "=");
checkLen(expectedLen, array.length);
out.println(TABLE_START_DECL);
for(double d : array){
for (double d : array) {
out.printf(" %s%n", format(d)); // one entry per line
}
out.println(TABLE_END_DECL);
@ -654,5 +655,4 @@ class AccurateMathCalc {
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

@ -391,7 +391,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 10);
double[] bD = generateDouble(r, 10);
@ -404,7 +404,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 10);
double[] bD = generateDouble(r, 10);
@ -416,7 +416,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 2);
double[] bD = generateDouble(r, 2);
@ -431,7 +431,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 2);
double[] bD = generateDouble(r, 2);
@ -445,7 +445,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 3);
double[] bD = generateDouble(r, 3);
@ -461,7 +461,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 3);
double[] bD = generateDouble(r, 3);
@ -476,7 +476,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = generateDouble(r, 4);
double[] bD = generateDouble(r, 4);
@ -493,7 +493,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
@Test
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) {
double[] aD = 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());
}
private double[] generateDouble (final UniformRandomProvider r, int n) {
private static double[] generateDouble(final UniformRandomProvider r, int n) {
double[] a = new double[n];
for (int i = 0; i < n; ++i) {
a[i] = r.nextDouble();
@ -545,7 +545,7 @@ public abstract class ExtendedFieldElementAbstractTest<T extends RealFieldElemen
return a;
}
private T[] toFieldArray (double[] a) {
private T[] toFieldArray(double[] a) {
T[] f = MathArrays.buildArray(build(0).getField(), a.length);
for (int i = 0; i < a.length; ++i) {
f[i] = build(a[i]);

View File

@ -1,15 +1,18 @@
/*
* 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.
* 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.
*/
package org.apache.commons.math4.legacy.core;
@ -168,7 +171,7 @@ public class IntegerSequenceTest {
Assert.assertEquals(seq.size(), r.size());
}
@Test(expected=MaxCountExceededException.class)
@Test(expected = MaxCountExceededException.class)
public void testIncrementorCountExceeded() {
final int start = 1;
final int max = 7;
@ -203,7 +206,7 @@ public class IntegerSequenceTest {
Assert.assertTrue(inc.canIncrement(0));
}
@Test(expected=NotStrictlyPositiveException.class)
@Test(expected = NotStrictlyPositiveException.class)
public void testIncrementZeroTimes() {
final int start = 1;
final int max = 2;
@ -245,7 +248,7 @@ public class IntegerSequenceTest {
}
}
@Test(expected=ZeroException.class)
@Test(expected = ZeroException.class)
public void testIncrementZeroStep() {
final int step = 0;
@ -298,7 +301,7 @@ public class IntegerSequenceTest {
}
}
@Test(expected=TooManyEvaluationsException.class)
@Test(expected = TooManyEvaluationsException.class)
public void testIncrementorAlternateException() {
final int start = 1;
final int max = 2;

View File

@ -1,15 +1,18 @@
/*
* 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.
* 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.
*/
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[] 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[] nullArray = null;
private double[] singletonArray = {0};
@Test
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[] correctScaled = new double[]{5.25, 2.1, 0, -2.1, -5.25};
@ -62,7 +64,7 @@ public class MathArraysTest {
@Test
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};
MathArrays.scaleInPlace(-2.1, test);
@ -72,27 +74,27 @@ public class MathArraysTest {
}
}
@Test(expected=DimensionMismatchException.class)
@Test(expected = DimensionMismatchException.class)
public void testEbeAddPrecondition() {
MathArrays.ebeAdd(new double[3], new double[4]);
}
@Test(expected=DimensionMismatchException.class)
@Test(expected = DimensionMismatchException.class)
public void testEbeSubtractPrecondition() {
MathArrays.ebeSubtract(new double[3], new double[4]);
}
@Test(expected=DimensionMismatchException.class)
@Test(expected = DimensionMismatchException.class)
public void testEbeMultiplyPrecondition() {
MathArrays.ebeMultiply(new double[3], new double[4]);
}
@Test(expected=DimensionMismatchException.class)
@Test(expected = DimensionMismatchException.class)
public void testEbeDividePrecondition() {
MathArrays.ebeDivide(new double[3], new double[4]);
}
@Test
public void testEbeAdd() {
final double[] a = { 0, 1, 2 };
final double[] b = { 3, 5, 7 };
final double[] a = {0, 1, 2};
final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeAdd(a, b);
for (int i = 0; i < a.length; i++) {
@ -101,28 +103,30 @@ public class MathArraysTest {
}
@Test
public void testEbeSubtract() {
final double[] a = { 0, 1, 2 };
final double[] b = { 3, 5, 7 };
final double[] a = {0, 1, 2};
final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeSubtract(a, b);
for (int i = 0; i < a.length; i++) {
Assert.assertEquals(a[i] - b[i], r[i], 0);
}
}
@Test
public void testEbeMultiply() {
final double[] a = { 0, 1, 2 };
final double[] b = { 3, 5, 7 };
final double[] a = {0, 1, 2};
final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeMultiply(a, b);
for (int i = 0; i < a.length; i++) {
Assert.assertEquals(a[i] * b[i], r[i], 0);
}
}
@Test
public void testEbeDivide() {
final double[] a = { 0, 1, 2 };
final double[] b = { 3, 5, 7 };
final double[] a = {0, 1, 2};
final double[] b = {3, 5, 7};
final double[] r = MathArrays.ebeDivide(a, b);
for (int i = 0; i < a.length; i++) {
@ -132,43 +136,43 @@ public class MathArraysTest {
@Test
public void testL1DistanceDouble() {
double[] p1 = { 2.5, 0.0 };
double[] p2 = { -0.5, 4.0 };
double[] p1 = {2.5, 0.0};
double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(7.0, MathArrays.distance1(p1, p2), 1));
}
@Test
public void testL1DistanceInt() {
int[] p1 = { 3, 0 };
int[] p2 = { 0, 4 };
int[] p1 = {3, 0};
int[] p2 = {0, 4};
Assert.assertEquals(7, MathArrays.distance1(p1, p2));
}
@Test
public void testL2DistanceDouble() {
double[] p1 = { 2.5, 0.0 };
double[] p2 = { -0.5, 4.0 };
double[] p1 = {2.5, 0.0};
double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(5.0, MathArrays.distance(p1, p2), 1));
}
@Test
public void testL2DistanceInt() {
int[] p1 = { 3, 0 };
int[] p2 = { 0, 4 };
int[] p1 = {3, 0};
int[] p2 = {0, 4};
Assert.assertTrue(Precision.equals(5, MathArrays.distance(p1, p2), 1));
}
@Test
public void testLInfDistanceDouble() {
double[] p1 = { 2.5, 0.0 };
double[] p2 = { -0.5, 4.0 };
double[] p1 = {2.5, 0.0};
double[] p2 = {-0.5, 4.0};
Assert.assertTrue(Precision.equals(4.0, MathArrays.distanceInf(p1, p2), 1));
}
@Test
public void testLInfDistanceInt() {
int[] p1 = { 3, 0 };
int[] p2 = { 0, 4 };
int[] p1 = {3, 0};
int[] p2 = {0, 4};
Assert.assertEquals(4, MathArrays.distanceInf(p1, p2));
}
@ -222,72 +226,72 @@ public class MathArraysTest {
@Test
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));
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));
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));
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));
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));
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));
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));
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));
}
@Test
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),
Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(-5.5),
new Double(-1),
new Double(0),
new Double(2),
new Double(15) },
MathArrays.OrderDirection.INCREASING, true));
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(-2),
new Double(2) },
MathArrays.OrderDirection.INCREASING, false));
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(-15),
Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(-15),
new Double(-5.5),
new Double(-1),
new Double(-1),
new Double(2) },
MathArrays.OrderDirection.INCREASING, false));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(3),
Assert.assertFalse(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(3),
new Double(-5.5),
new Double(-11),
new Double(-27.5) },
MathArrays.OrderDirection.DECREASING, true));
Assert.assertTrue(MathArrays.isMonotonic(new Double[] { new Double(3),
Assert.assertTrue(MathArrays.isMonotonic(new Double[] {new Double(3),
new Double(2),
new Double(-5.5),
new Double(-11),
new Double(-27.5) },
MathArrays.OrderDirection.DECREASING, true));
Assert.assertFalse(MathArrays.isMonotonic(new Double[] { new Double(3),
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));
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(-5.5),
@ -386,7 +390,7 @@ public class MathArraysTest {
@Test
public void testCheckNotNaN() {
final double[] withoutNaN = { Double.NEGATIVE_INFINITY,
final double[] withoutNaN = {Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE,
-1, 0,
Double.MIN_VALUE,
@ -395,7 +399,7 @@ public class MathArraysTest {
Double.MAX_VALUE,
Double.POSITIVE_INFINITY };
final double[] withNaN = { Double.NEGATIVE_INFINITY,
final double[] withNaN = {Double.NEGATIVE_INFINITY,
-Double.MAX_VALUE,
-1, 0,
Double.MIN_VALUE,
@ -424,7 +428,7 @@ public class MathArraysTest {
}
}
@Test(expected=DimensionMismatchException.class)
@Test(expected = DimensionMismatchException.class)
public void testCheckEqualLength1() {
MathArrays.checkEqualLength(new double[] {1, 2, 3},
new double[] {1, 2, 3, 4});
@ -439,41 +443,41 @@ public class MathArraysTest {
@Test
public void testArrayEquals() {
Assert.assertFalse(MathArrays.equals(new double[] { 1d }, null));
Assert.assertFalse(MathArrays.equals(null, new double[] { 1d }));
Assert.assertFalse(MathArrays.equals(new double[] {1d}, null));
Assert.assertFalse(MathArrays.equals(null, new double[] {1d}));
Assert.assertTrue(MathArrays.equals((double[]) null, (double[]) null));
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[] { Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d },
new double[] { Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d }));
Assert.assertFalse(MathArrays.equals(new double[] { Double.NaN },
new double[] { Double.NaN }));
Assert.assertFalse(MathArrays.equals(new double[] { Double.POSITIVE_INFINITY },
new double[] { Double.NEGATIVE_INFINITY }));
Assert.assertFalse(MathArrays.equals(new double[] { 1d },
new double[] { AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d) }));
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[] {Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d},
new double[] {Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d}));
Assert.assertFalse(MathArrays.equals(new double[] {Double.NaN},
new double[] {Double.NaN}));
Assert.assertFalse(MathArrays.equals(new double[] {Double.POSITIVE_INFINITY},
new double[] {Double.NEGATIVE_INFINITY}));
Assert.assertFalse(MathArrays.equals(new double[] {1d},
new double[] {AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d)}));
}
@Test
public void testArrayEqualsIncludingNaN() {
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { 1d }, null));
Assert.assertFalse(MathArrays.equalsIncludingNaN(null, new double[] { 1d }));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {1d}, null));
Assert.assertFalse(MathArrays.equalsIncludingNaN(null, new double[] {1d}));
Assert.assertTrue(MathArrays.equalsIncludingNaN((double[]) null, (double[]) null));
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[] { Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d },
new double[] { Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d }));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { Double.POSITIVE_INFINITY },
new double[] { Double.NEGATIVE_INFINITY }));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] { 1d },
new double[] { AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d) }));
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[] {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d},
new double[] {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, 1d, 0d}));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {Double.POSITIVE_INFINITY},
new double[] {Double.NEGATIVE_INFINITY}));
Assert.assertFalse(MathArrays.equalsIncludingNaN(new double[] {1d},
new double[] {AccurateMath.nextAfter(AccurateMath.nextAfter(1d, 2d), 2d)}));
}
@Test
@ -490,7 +494,7 @@ public class MathArraysTest {
// Ignore NaNs
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),
Double.MIN_VALUE);
@ -499,26 +503,26 @@ public class MathArraysTest {
try {
MathArrays.normalizeArray(zeroSum, 1);
Assert.fail("expecting MathArithmeticException");
} catch (MathArithmeticException ex) {}
} catch (MathArithmeticException ex) { /* ignore */ }
// Infinite elements -> MathArithmeticException
double[] hasInf = new double[] {1, 2, 1, Double.NEGATIVE_INFINITY};
try {
MathArrays.normalizeArray(hasInf, 1);
Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {}
} catch (MathIllegalArgumentException ex) { /* ignore */ }
// Infinite target -> MathIllegalArgumentException
try {
MathArrays.normalizeArray(testValues1, Double.POSITIVE_INFINITY);
Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {}
} catch (MathIllegalArgumentException ex) { /* ignore */ }
// NaN target -> MathIllegalArgumentException
try {
MathArrays.normalizeArray(testValues1, Double.NaN);
Assert.fail("expecting MathIllegalArgumentException");
} catch (MathIllegalArgumentException ex) {}
} catch (MathIllegalArgumentException ex) { /* ignore */ }
}
@Test
@ -528,17 +532,17 @@ public class MathArraysTest {
* h=[1,0.8,0.5,0.3]
* 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[] h1 = { 1, 0.8, 0.5, 0.3 };
double[] y1 = { 1.2, -0.84, 0.56, 0.58, 0.16, 0.42 };
double[] x1 = {1.2, -1.8, 1.4};
double[] h1 = {1, 0.8, 0.5, 0.3};
double[] y1 = {1.2, -0.84, 0.56, 0.58, 0.16, 0.42};
double tolerance = 1e-13;
double[] yActual = MathArrays.convolve(x1, h1);
Assert.assertArrayEquals(y1, yActual, tolerance);
double[] x2 = { 1, 2, 3 };
double[] h2 = { 0, 1, 0.5 };
double[] y2 = { 0, 1, 2.5, 4, 1.5 };
double[] x2 = {1, 2, 3};
double[] h2 = {0, 1, 0.5};
double[] y2 = {0, 1, 2.5, 4, 1.5};
yActual = MathArrays.convolve(x2, h2);
Assert.assertArrayEquals(y2, yActual, tolerance);
@ -628,6 +632,7 @@ public class MathArraysTest {
@Test
public void testVerifyValuesNegative() {
final double[] nullArray = null;
Assert.assertFalse(MathArrays.verifyValues(singletonArray, 0, 0));
Assert.assertFalse(MathArrays.verifyValues(testArray, 0, 0));
try {
@ -706,7 +711,7 @@ public class MathArraysTest {
Assert.assertEquals(0, MathArrays.concatenate(z, z, z).length);
}
@Test(expected=NullPointerException.class)
@Test(expected = NullPointerException.class)
public void testConcatenateNullArguments() {
final double[] x = new double[] {0, 1, 2};
MathArrays.concatenate(x, null);
@ -721,10 +726,10 @@ public class MathArraysTest {
@Test
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};
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
@ -740,7 +745,7 @@ public class MathArraysTest {
Assert.assertEquals(Double.NEGATIVE_INFINITY, u[4], 0);
}
@Test(expected=NullPointerException.class)
@Test(expected = NullPointerException.class)
public void testUniqueNullArgument() {
MathArrays.unique(null);
}

View File

@ -1,15 +1,18 @@
/*
* 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.
* 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.
*/
package org.apache.commons.math4.legacy.core;
@ -93,12 +96,12 @@ public class PairTest {
private static class MyInteger {
private int i;
public MyInteger(int i) {
MyInteger(int i) {
this.i = i;
}
public void set(int i) {
this.i = i;
public void set(int value) {
this.i = value;
}
@Override

View File

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

View File

@ -56,28 +56,29 @@ public class DfpMathTest {
// Generic test function. Takes params x and y and tests them for
// equality. Then checks the status flags against the flags argument.
// 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);
if (!x.equals(y) && !x.unequal(y)) // NaNs involved
b = (x.toString().equals(y.toString()));
if (!x.equals(y) && !x.unequal(y)) { // NaNs involved
b = x.toString().equals(y.toString());
}
if (x.equals(factory.newDfp("0"))) // distinguish +/- zero
b = (b && (x.toString().equals(y.toString())));
if (x.equals(factory.newDfp("0"))) { // distinguish +/- zero
b = b && (x.toString().equals(y.toString()));
}
b = (b && x.getField().getIEEEFlags() == flags);
b = b && x.getField().getIEEEFlags() == flags;
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();
}
@Test
public void testPow()
{
public void testPow() {
// Test special cases exponent of zero
test(DfpMath.pow(factory.newDfp("0"), factory.newDfp("0")),
factory.newDfp("1"),
@ -464,24 +465,23 @@ public class DfpMathTest {
test(DfpMath.pow(factory.newDfp("-2"), factory.newDfp("-4.1")),
qnan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "pow #87");
DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "pow #87");
// 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"),
DfpField.FLAG_INEXACT, "pow #88");
}
@Test
public void testSin()
{
public void testSin() {
test(DfpMath.sin(pinf),
nan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "sin #1");
DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "sin #1");
test(DfpMath.sin(nan),
nan,
DfpField.FLAG_INVALID|DfpField.FLAG_INEXACT, "sin #2");
DfpField.FLAG_INVALID | DfpField.FLAG_INEXACT, "sin #2");
test(DfpMath.sin(factory.getZero()),
factory.getZero(),

View File

@ -27,11 +27,6 @@ import org.junit.Test;
public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Override
protected Dfp build(final double x) {
return field.newDfp(x);
}
private DfpField field;
private Dfp pinf;
private Dfp ninf;
@ -39,6 +34,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
private Dfp snan;
private Dfp qnan;
@Override
protected Dfp build(final double x) {
return field.newDfp(x);
}
@Before
public void setUp() {
// 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) {
boolean b = x.equals(y);
if (!x.equals(y) && !x.unequal(y)) // NaNs involved
b = (x.toString().equals(y.toString()));
if (!x.equals(y) && !x.unequal(y)) { // NaNs involved
b = x.toString().equals(y.toString());
}
if (x.equals(field.newDfp("0"))) // distinguish +/- zero
b = (b && (x.toString().equals(y.toString())));
if (x.equals(field.newDfp("0"))) { // distinguish +/- zero
b = b && (x.toString().equals(y.toString()));
}
b = (b && x.getField().getIEEEFlags() == flags);
b = b && x.getField().getIEEEFlags() == flags;
if (!b)
Assert.assertTrue("assertion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b);
if (!b) {
Assert.assertTrue(
"assertion failed " + desc + " x = " + x.toString() + " flags = " + x.getField().getIEEEFlags(), b);
}
x.getField().clearIEEEFlags();
}
@ -103,11 +107,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Test
public void testLongConstructor() {
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("1234567890.", new Dfp(field, 1234567890l).toString());
Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890l).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("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("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString());
}
@ -370,25 +374,25 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
// utility function to help test comparisons
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) {
assertionFailOpNum(op, num);
}
}
if (op == "unequal") {
if (op.equals("unequal")) {
if (a.unequal(b) != result) {
assertionFailOpNum(op, num);
}
}
if (op == "lessThan") {
if (op.equals("lessThan")) {
if (a.lessThan(b) != result) {
assertionFailOpNum(op, num);
}
}
if (op == "greaterThan") {
if (op.equals("greaterThan")) {
if (a.greaterThan(b) != result) {
assertionFailOpNum(op, num);
}
@ -580,7 +584,7 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
cmptst(qnan.negate(), qnan, "unequal", false, 52);
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
if (field.getIEEEFlags() != DfpField.FLAG_INVALID) {
assertionFail("compare lessThan flags = "+field.getIEEEFlags());
assertionFail("compare lessThan flags = " + field.getIEEEFlags());
}
field.clearIEEEFlags();
@ -767,9 +771,9 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
cmptst(snan.negate(), snan, "greaterThan", false, 51);
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) {
assertionFail("compare greaterThan flags = "+field.getIEEEFlags());
assertionFail("compare greaterThan flags = " + field.getIEEEFlags());
}
field.clearIEEEFlags();
}
@ -1220,15 +1224,15 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
test(field.newDfp("-1e-131092").nextAfter(pinf),
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),
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),
pinf,
DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14");
DfpField.FLAG_OVERFLOW | DfpField.FLAG_INEXACT, "Next After #14");
}
@Test
@ -1563,11 +1567,11 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
@Test
public void testIssue567() {
DfpField field = new DfpField(100);
Assert.assertEquals(0.0, field.getZero().toDouble(), Precision.SAFE_MIN);
Assert.assertEquals(0.0, field.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, field.newDfp(+0.0).toDouble()), Precision.EPSILON);
DfpField localField = new DfpField(100);
Assert.assertEquals(0.0, localField.getZero().toDouble(), Precision.SAFE_MIN);
Assert.assertEquals(0.0, localField.newDfp(0.0).toDouble(), Precision.SAFE_MIN);
Assert.assertEquals(-1, AccurateMath.copySign(1, localField.newDfp(-0.0).toDouble()), Precision.EPSILON);
Assert.assertEquals(+1, AccurateMath.copySign(1, localField.newDfp(+0.0).toDouble()), Precision.EPSILON);
}
@Test
@ -1660,15 +1664,15 @@ public class DfpTest extends ExtendedFieldElementAbstractTest<Dfp> {
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);
}
private static void assertionFailOpNum(String op, double num){
private static void assertionFailOpNum(String op, double num) {
assertionFail(op + " compare #" + num);
}
private static final void assertionFailDfpField(DfpField field){
private static void assertionFailDfpField(DfpField field) {
assertionFail("compare flags = " + field.getIEEEFlags());
}
}

View File

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

View File

@ -42,6 +42,8 @@ import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
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 int NUMBER_OF_TRIALS = 1000;
@ -52,22 +54,22 @@ public class AccurateMathTest {
@Before
public void setUp() {
field = new DfpField(40);
generator = RandomSource.create(RandomSource.MT, 6176597458463500194l);
generator = RandomSource.create(RandomSource.MT, 6176597458463500194L);
}
@Test
public void testMinMaxDouble() {
double[][] pairs = {
{ -50.0, 50.0 },
{ Double.POSITIVE_INFINITY, 1.0 },
{ Double.NEGATIVE_INFINITY, 1.0 },
{ Double.NaN, 1.0 },
{ Double.POSITIVE_INFINITY, 0.0 },
{ Double.NEGATIVE_INFINITY, 0.0 },
{ Double.NaN, 0.0 },
{ Double.NaN, Double.NEGATIVE_INFINITY },
{ Double.NaN, Double.POSITIVE_INFINITY },
{ Precision.SAFE_MIN, Precision.EPSILON }
{-50.0, 50.0},
{Double.POSITIVE_INFINITY, 1.0},
{Double.NEGATIVE_INFINITY, 1.0},
{Double.NaN, 1.0},
{Double.POSITIVE_INFINITY, 0.0},
{Double.NEGATIVE_INFINITY, 0.0},
{Double.NaN, 0.0},
{Double.NaN, Double.NEGATIVE_INFINITY},
{Double.NaN, Double.POSITIVE_INFINITY},
{Precision.SAFE_MIN, Precision.EPSILON}
};
for (double[] pair : pairs) {
assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
@ -92,15 +94,15 @@ public class AccurateMathTest {
@Test
public void testMinMaxFloat() {
float[][] pairs = {
{ -50.0f, 50.0f },
{ Float.POSITIVE_INFINITY, 1.0f },
{ Float.NEGATIVE_INFINITY, 1.0f },
{ Float.NaN, 1.0f },
{ Float.POSITIVE_INFINITY, 0.0f },
{ Float.NEGATIVE_INFINITY, 0.0f },
{ Float.NaN, 0.0f },
{ Float.NaN, Float.NEGATIVE_INFINITY },
{ Float.NaN, Float.POSITIVE_INFINITY }
{-50.0f, 50.0f},
{Float.POSITIVE_INFINITY, 1.0f},
{Float.NEGATIVE_INFINITY, 1.0f},
{Float.NaN, 1.0f},
{Float.POSITIVE_INFINITY, 0.0f},
{Float.NEGATIVE_INFINITY, 0.0f},
{Float.NaN, 0.0f},
{Float.NaN, Float.NEGATIVE_INFINITY},
{Float.NaN, Float.POSITIVE_INFINITY}
};
for (float[] pair : pairs) {
assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
@ -413,11 +415,10 @@ public class AccurateMathTest {
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() {
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,
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,
@ -558,11 +559,15 @@ public class AccurateMathTest {
for (double i : DOUBLES) {
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 (i % 2.0 == 0.0) assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
if (i % 2.0 == 0.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 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 if (Math.abs(i) % 2.0 == 1.0) assertEquals(-AccurateMath.pow(-d, i), 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.
else assertEquals(Double.NaN, AccurateMath.pow(d, i), EXACT);
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.
for (double d : DOUBLES) {
if (d % 1.0 == 0.0) {
boolean dNegative = Double.doubleToRawLongBits( d ) < 0L;
boolean dNegative = Double.doubleToRawLongBits(d) < 0L;
for (double i : DOUBLES) {
if (i % 1.0 == 0.0) {
BigInteger bd = BigDecimal.valueOf(d).toBigInteger().abs();
@ -588,10 +593,10 @@ public class AccurateMathTest {
} else if (res.signum() == 0) {
expected = Double.POSITIVE_INFINITY;
} 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;
}
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);
assertEquals("atan2(-Inf, Inf) should be -PI/4", -AccurateMath.PI / 4.0, AccurateMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY),
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);
}
@ -891,7 +896,7 @@ public class AccurateMathTest {
public void testAsinAccuracy() {
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 tst = AccurateMath.asin(x);
@ -914,7 +919,7 @@ public class AccurateMathTest {
public void testAcosAccuracy() {
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 tst = AccurateMath.acos(x);
@ -977,7 +982,7 @@ public class AccurateMathTest {
public void testSinhAccuracy() {
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 tst = AccurateMath.sinh(x);
@ -999,7 +1004,7 @@ public class AccurateMathTest {
public void testCoshAccuracy() {
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 tst = AccurateMath.cosh(x);
@ -1021,7 +1026,7 @@ public class AccurateMathTest {
public void testTanhAccuracy() {
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 tst = AccurateMath.tanh(x);
@ -1043,7 +1048,7 @@ public class AccurateMathTest {
public void testCbrtAccuracy() {
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 tst = AccurateMath.cbrt(x);
@ -1062,7 +1067,7 @@ public class AccurateMathTest {
}
private Dfp cbrt(Dfp x) {
boolean negative=false;
boolean negative = false;
if (x.lessThan(field.getZero())) {
negative = true;
@ -1187,11 +1192,11 @@ public class AccurateMathTest {
@Test
public void testDoubleNextAfterSpecialCases() {
assertEquals(-Double.MAX_VALUE,AccurateMath.nextAfter(Double.NEGATIVE_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.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.MAX_VALUE, AccurateMath.nextAfter(Double.NEGATIVE_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.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.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);
@ -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, 2048), 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.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.POSITIVE_INFINITY, AccurateMath.scalb( 2.2250738585072014E-308, 2147483647), 0D);
assertEquals(Double.POSITIVE_INFINITY, AccurateMath.scalb(+2.2250738585072014E-308, 2147483647), 0D);
}
@Test
@ -1253,16 +1258,16 @@ public class AccurateMathTest {
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;
for(Method method1 : class1.getDeclaredMethods()){
if (Modifier.isPublic(method1.getModifiers())){
Type []params = method1.getGenericParameterTypes();
for (Method method1 : class1.getDeclaredMethods()) {
if (Modifier.isPublic(method1.getModifiers())) {
Type[] params = method1.getGenericParameterTypes();
try {
class2.getDeclaredMethod(method1.getName(), (Class[]) params);
} catch (NoSuchMethodException e) {
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
public void testIntPow() {
final int maxExp = 300;
DfpField field = new DfpField(40);
DfpField localField = new DfpField(40);
final double base = 1.23456789;
Dfp baseDfp = field.newDfp(base);
Dfp dfpPower = field.getOne();
Dfp baseDfp = localField.newDfp(base);
Dfp dfpPower = localField.getOne();
for (int i = 0; i < maxExp; i++) {
assertEquals("exp=" + i, dfpPower.toDouble(), AccurateMath.pow(base, i),
0.6 * AccurateMath.ulp(dfpPower.toDouble()));
@ -1353,16 +1358,15 @@ public class AccurateMathTest {
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() {
assertEquals(1.0, AccurateMath.pow(1.0, Long.MIN_VALUE), -1.0);
}
@Test(timeout=5000L)
@Test(timeout = 5000L)
public void testIntPowSpecialCases() {
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,
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,
@ -1374,7 +1378,7 @@ public class AccurateMathTest {
-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:
// If the second argument is positive or negative zero, then the result is 1.0.
for (double d : DOUBLES) {
@ -1515,9 +1519,12 @@ public class AccurateMathTest {
if (d < 0.0 && Math.abs(d) <= Double.MAX_VALUE) {
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 ((i & 1L) == 0L) assertEquals(AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
if ((i & 1L) == 0L) {
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
else assertEquals(-AccurateMath.pow(-d, i), AccurateMath.pow(d, i), EXACT);
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.
}
}
@ -1752,23 +1759,23 @@ public class AccurateMathTest {
}
}
@Test(expected=MathArithmeticException.class)
@Test(expected = MathArithmeticException.class)
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() {
AccurateMath.toIntExact(+1l + Integer.MAX_VALUE);
AccurateMath.toIntExact(+1L + Integer.MAX_VALUE);
}
@Test
public void testToIntExact() {
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.MAX_VALUE, AccurateMath.toIntExact(0l + Integer.MAX_VALUE));
assertEquals(Integer.MIN_VALUE, AccurateMath.toIntExact(0L + Integer.MIN_VALUE));
assertEquals(Integer.MAX_VALUE, AccurateMath.toIntExact(0L + Integer.MAX_VALUE));
}
@Test
@ -1815,11 +1822,11 @@ public class AccurateMathTest {
@Test
public void testFloorDivModInt() {
UniformRandomProvider generator = RandomSource.create(RandomSource.WELL_1024_A,
0x7ccab45edeaab90al);
UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_1024_A,
0x7ccab45edeaab90aL);
for (int i = 0; i < 10000; ++i) {
int a = generator.nextInt();
int b = generator.nextInt();
int a = rng.nextInt();
int b = rng.nextInt();
if (b == 0) {
try {
AccurateMath.floorDiv(a, b);
@ -1846,18 +1853,18 @@ public class AccurateMathTest {
@Test
public void testFloorDivLong() {
assertEquals(+1l, 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));
assertEquals(-2L, AccurateMath.floorDiv(-4L, +3L));
assertEquals(-2L, AccurateMath.floorDiv(+4L, -3L));
assertEquals(+1L, AccurateMath.floorDiv(-4L, -3L));
try {
AccurateMath.floorDiv(1l, 0l);
AccurateMath.floorDiv(1L, 0L);
fail("an exception should have been thrown");
} catch (MathArithmeticException mae) {
// expected
}
for (long a = -100l; a <= 100l; ++a) {
for (long b = -100l; b <= 100l; ++b) {
for (long a = -100L; a <= 100L; ++a) {
for (long b = -100L; b <= 100L; ++b) {
if (b != 0) {
assertEquals(poorManFloorDiv(a, b), AccurateMath.floorDiv(a, b));
}
@ -1867,18 +1874,18 @@ public class AccurateMathTest {
@Test
public void testFloorModLong() {
assertEquals(+1l, 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));
assertEquals(+2L, AccurateMath.floorMod(-4L, +3L));
assertEquals(-2L, AccurateMath.floorMod(+4L, -3L));
assertEquals(-1L, AccurateMath.floorMod(-4L, -3L));
try {
AccurateMath.floorMod(1l, 0l);
AccurateMath.floorMod(1L, 0L);
fail("an exception should have been thrown");
} catch (MathArithmeticException mae) {
// expected
}
for (long a = -100l; a <= 100l; ++a) {
for (long b = -100l; b <= 100l; ++b) {
for (long a = -100L; a <= 100L; ++a) {
for (long b = -100L; b <= 100L; ++b) {
if (b != 0) {
assertEquals(poorManFloorMod(a, b), AccurateMath.floorMod(a, b));
}
@ -1888,11 +1895,11 @@ public class AccurateMathTest {
@Test
public void testFloorDivModLong() {
UniformRandomProvider generator = RandomSource.create(RandomSource.WELL_1024_A,
0xb87b9bc14c96ccd5l);
UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_1024_A,
0xb87b9bc14c96ccd5L);
for (int i = 0; i < 10000; ++i) {
long a = generator.nextLong();
long b = generator.nextLong();
long a = rng.nextLong();
long b = rng.nextLong();
if (b == 0) {
try {
AccurateMath.floorDiv(a, b);
@ -1931,7 +1938,7 @@ public class AccurateMathTest {
BigInteger q = q0.subtract(bigK);
BigInteger r = r0.add(bigK.multiply(bigB));
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) {
fd = q;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,7 +35,7 @@ public class NotFiniteNumberException extends MathIllegalNumberException {
* @param args Optional arguments.
*/
public NotFiniteNumberException(Number wrong,
Object ... args) {
Object... args) {
this(LocalizedFormats.NOT_FINITE_NUMBER, wrong, args);
}
@ -48,7 +48,7 @@ public class NotFiniteNumberException extends MathIllegalNumberException {
*/
public NotFiniteNumberException(Localizable specific,
Number wrong,
Object ... args) {
Object... 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}.
*/
public NullArgumentException(Localizable pattern,
Object ... arguments) {
Object... arguments) {
context = new ExceptionContext(this);
context.addMessage(pattern, arguments);
}
@ -91,7 +91,7 @@ public class NullArgumentException extends NullPointerException
*/
public static void check(Object o,
Localizable pattern,
Object ... args) {
Object... args) {
if (o == null) {
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 {
/** Serializable version identifier */
/** Serializable version identifier. */
private static final long serialVersionUID = -1960874856936000015L;
/**
@ -42,7 +42,7 @@ public class ZeroException extends MathIllegalNumberException {
* @param specific Specific context pattern.
* @param arguments Arguments.
*/
public ZeroException(Localizable specific, Object ... arguments) {
public ZeroException(Localizable specific, Object... 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
* constructors of exceptions.
*
*/
public class ArgUtils {
public final class ArgUtils {
/**
* Class contains only static methods.
*/

View File

@ -82,7 +82,7 @@ public class ExceptionContext implements Serializable {
* pattern.
*/
public void addMessage(Localizable pattern,
Object ... arguments) {
Object... arguments) {
msgPatterns.add(pattern);
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.
*/
@ -285,7 +285,7 @@ public class ExceptionContext implements Serializable {
// Step 1.
final int len = context.size();
out.writeInt(len);
for (Map.Entry<String,Object> entry : context.entrySet()) {
for (Map.Entry<String, Object> entry : context.entrySet()) {
// Step 2.
out.writeObject(entry.getKey());
final Object value = entry.getValue();
@ -328,7 +328,7 @@ public class ExceptionContext implements Serializable {
* interface.
* @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() + "]";
}
}

View File

@ -1,23 +1,24 @@
/*
* 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.
* 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.
*/
package org.apache.commons.math4.legacy.exception;
import org.junit.Assert;
import org.junit.Test;
import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
/**
* Tests for {@link NotFiniteNumberException}.
*/

View File

@ -1,19 +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.
* 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.
*/
package org.apache.commons.math4.legacy.exception;
import org.junit.Assert;
import org.junit.Test;
import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;

View File

@ -107,7 +107,6 @@ public class ExceptionContextTest {
String key = "Key 1";
cOut.setValue(key, new Unserializable());
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(cOut);
@ -119,7 +118,6 @@ public class ExceptionContextTest {
String nsObjStr = (String) cIn.getValue(key);
Assert.assertTrue(nsObjStr.matches(".*could not be serialized.*"));
}
}
/**
* Class used by {@link #testSerializeUnserializable()}.

View File

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

View File

@ -145,6 +145,14 @@
<skip>true</skip>
</configuration>
</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>
</build>

View File

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

View File

@ -26,7 +26,7 @@ import org.apache.commons.math4.neuralnet.internal.NeuralNetException;
*
* @since 3.3
*/
public class MapUtils {
public final class MapUtils {
/**
* 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
*/
public class NeuronString implements Serializable {
/** Serial version ID */
/** Serial version ID. */
private static final long serialVersionUID = 1L;
/** Underlying network. */
private final Network network;

View File

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

View File

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

View File

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

View File

@ -66,7 +66,7 @@ public class QuasiSigmoidDecayFunction implements LongToDoubleFunction {
final double k = initValue;
final double m = numCall;
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);
scale = k / y0;

View File

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

View File

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

View File

@ -43,7 +43,7 @@ public class MapRankingTest {
final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
final FeatureInitializer init
= 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(),
new EuclideanDistance());
@ -60,8 +60,8 @@ public class MapRankingTest {
best.clear();
features = new double[][] {
{ -1 },
{ 0.4 },
{-1 },
{0.4 },
};
for (double[] f : features) {
best.addAll(ranking.rank(f, 1));
@ -71,8 +71,8 @@ public class MapRankingTest {
best.clear();
features = new double[][] {
{ 0.6 },
{ 1.4 },
{0.6 },
{1.4 },
};
for (double[] f : features) {
best.addAll(ranking.rank(f, 1));
@ -82,8 +82,8 @@ public class MapRankingTest {
best.clear();
features = new double[][] {
{ 1.6 },
{ 3 },
{1.6 },
{3 },
};
for (double[] f : features) {
best.addAll(ranking.rank(f, 1));
@ -94,15 +94,15 @@ public class MapRankingTest {
Assert.assertEquals(3, allBest.size());
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testRankPrecondition() {
final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
final FeatureInitializer init
= 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 EuclideanDistance()).rank(new double[] { -1 }, 0);
new EuclideanDistance()).rank(new double[] {-1}, 0);
}
@Test
@ -110,13 +110,13 @@ public class MapRankingTest {
final Set<Neuron> list = new HashSet<>();
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 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++) {
Assert.assertEquals(expected[i], sorted.get(i).getIdentifier());
}

View File

@ -42,7 +42,7 @@ public class NetworkTest {
@Test
public void testGetFeaturesSize() {
final FeatureInitializer[] initArray = { init, init, init };
final FeatureInitializer[] initArray = {init, init, init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
@ -61,7 +61,7 @@ public class NetworkTest {
*/
@Test
public void testDeleteLink() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
SquareNeighbourhood.VON_NEUMANN,
@ -90,7 +90,7 @@ public class NetworkTest {
*/
@Test
public void testDeleteNeuron() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
SquareNeighbourhood.VON_NEUMANN,
@ -104,7 +104,9 @@ public class NetworkTest {
try {
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(3)).size());
@ -112,7 +114,7 @@ public class NetworkTest {
@Test
public void testIterationOrder() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(4, false,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -142,7 +144,7 @@ public class NetworkTest {
*/
@Test
public void testCopy() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
SquareNeighbourhood.VON_NEUMANN,
@ -177,7 +179,7 @@ public class NetworkTest {
public void testSerialize()
throws IOException,
ClassNotFoundException {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network out = new NeuronSquareMesh2D(4, false,
3, true,
SquareNeighbourhood.VON_NEUMANN,

View File

@ -33,21 +33,21 @@ public class NeuronTest {
@Test
public void testGetIdentifier() {
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());
}
@Test
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);
Assert.assertEquals(features.length, n.getSize());
}
@Test
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 double[] f = n.getFeatures();
@ -63,9 +63,9 @@ public class NeuronTest {
@Test
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[] update = new double[] { expect[0] + 1.23 };
double[] update = new double[] {expect[0] + 1.23};
// Test "success".
boolean ok = n.compareAndSetFeatures(expect, update);
@ -75,7 +75,7 @@ public class NeuronTest {
Assert.assertEquals(update[0], n.getFeatures()[0], 0d);
// 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
// updated: a new update can only succeed if "expect"
// is set to the new features.
@ -88,10 +88,10 @@ public class NeuronTest {
@Test
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.
double[] update = new double[] { n.getFeatures()[0] + 2.34 };
double[] update = new double[] {n.getFeatures()[0] + 2.34};
n.compareAndSetFeatures(n.getFeatures(), update);
// Create a copy.
@ -103,7 +103,7 @@ public class NeuronTest {
copy.getNumberOfAttemptedUpdates());
// Update original.
update = new double[] { 1.23 * n.getFeatures()[0] };
update = new double[] {1.23 * n.getFeatures()[0]};
n.compareAndSetFeatures(n.getFeatures(), update);
// Check that original and copy differ.
@ -116,7 +116,7 @@ public class NeuronTest {
public void testSerialize()
throws IOException,
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 ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(out);

View File

@ -17,7 +17,6 @@
package org.apache.commons.math4.neuralnet;
/**
* Wraps a given initializer.
*/

View File

@ -51,14 +51,14 @@ public class NeuronStringTest {
*/
@Test
public void testSegmentNetwork() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(4, false, initArray).getNetwork();
Collection<Neuron> neighbours;
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -66,7 +66,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -74,7 +74,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -82,7 +82,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -96,14 +96,14 @@ public class NeuronStringTest {
*/
@Test
public void testCircleNetwork() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(4, true, initArray).getNetwork();
Collection<Neuron> neighbours;
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -111,7 +111,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -119,7 +119,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -127,7 +127,7 @@ public class NeuronStringTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -141,7 +141,7 @@ public class NeuronStringTest {
*/
@Test
public void testGetNeighboursWithExclude() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronString(5, true, initArray).getNetwork();
final Collection<Neuron> exclude = new ArrayList<>();
exclude.add(net.getNeuron(1));
@ -155,7 +155,7 @@ public class NeuronStringTest {
public void testSerialize()
throws IOException,
ClassNotFoundException {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronString out = new NeuronString(4, false, initArray);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();

View File

@ -49,7 +49,7 @@ public class KohonenUpdateActionTest {
public void testUpdate() {
final FeatureInitializer init
= new OffsetFeatureInitializer(FeatureInitializerFactory.uniform(rng, 0, 0.1));
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final int netSize = 3;
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,
// 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];
int count = 0;
for (Neuron n : net) {

View File

@ -24,23 +24,23 @@ import org.junit.Assert;
* Tests for {@link LearningFactorFunctionFactory} class.
*/
public class LearningFactorFunctionFactoryTest {
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition0() {
LearningFactorFunctionFactory.exponentialDecay(0d, 0d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition1() {
LearningFactorFunctionFactory.exponentialDecay(1 + 1e-10, 0d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition2() {
LearningFactorFunctionFactory.exponentialDecay(1d, 0d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition3() {
LearningFactorFunctionFactory.exponentialDecay(1d, 1d, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition4() {
LearningFactorFunctionFactory.exponentialDecay(1d, 0.2, 0);
}
@ -58,19 +58,19 @@ public class LearningFactorFunctionFactoryTest {
Assert.assertEquals(0, f.value(Long.MAX_VALUE), 0d);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition0() {
LearningFactorFunctionFactory.quasiSigmoidDecay(0d, -1d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition1() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1 + 1e-10, -1d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition3() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1d, 0d, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition4() {
LearningFactorFunctionFactory.quasiSigmoidDecay(1d, -1d, 0);
}

View File

@ -24,19 +24,19 @@ import org.junit.Assert;
* Tests for {@link NeighbourhoodSizeFunctionFactory} class.
*/
public class NeighbourhoodSizeFunctionFactoryTest {
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition1() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(0, 0, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition2() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 0, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition3() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(1, 1, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testExponentialDecayPrecondition4() {
NeighbourhoodSizeFunctionFactory.exponentialDecay(2, 1, 0);
}
@ -54,15 +54,15 @@ public class NeighbourhoodSizeFunctionFactoryTest {
Assert.assertEquals(0, f.value(Long.MAX_VALUE));
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition1() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(0d, -1d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition3() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, 0d, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testQuasiSigmoidDecayPrecondition4() {
NeighbourhoodSizeFunctionFactory.quasiSigmoidDecay(1d, -1d, 0);
}

View File

@ -24,19 +24,19 @@ import org.junit.Assert;
* Tests for {@link ExponentialDecayFunction} class
*/
public class ExponentialDecayFunctionTest {
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition1() {
new ExponentialDecayFunction(0d, 0d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition2() {
new ExponentialDecayFunction(1d, 0d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition3() {
new ExponentialDecayFunction(1d, 1d, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition4() {
new ExponentialDecayFunction(1d, 0.2, 0);
}

View File

@ -24,15 +24,15 @@ import org.junit.Assert;
* Tests for {@link QuasiSigmoidDecayFunction} class
*/
public class QuasiSigmoidDecayFunctionTest {
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition1() {
new QuasiSigmoidDecayFunction(0d, -1d, 2);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition3() {
new QuasiSigmoidDecayFunction(1d, 0d, 100);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testPrecondition4() {
new QuasiSigmoidDecayFunction(1d, -1d, 0);
}

View File

@ -49,9 +49,9 @@ public class NeuronSquareMesh2DTest {
private final UniformRandomProvider rng = RandomSource.create(RandomSource.SPLIT_MIX_64);
private final FeatureInitializer init = FeatureInitializerFactory.uniform(rng, 0, 2);
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testMinimalNetworkSize1() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
new NeuronSquareMesh2D(1, false,
2, false,
@ -59,9 +59,9 @@ public class NeuronSquareMesh2DTest {
initArray);
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void testMinimalNetworkSize2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
new NeuronSquareMesh2D(2, false,
0, false,
@ -71,7 +71,7 @@ public class NeuronSquareMesh2DTest {
@Test
public void testGetFeaturesSize() {
final FeatureInitializer[] initArray = { init, init, init };
final FeatureInitializer[] initArray = {init, init, init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
@ -91,7 +91,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test2x2Network() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
SquareNeighbourhood.VON_NEUMANN,
@ -99,9 +99,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours;
// Neurons 0 and 3.
for (long id : new long[] { 0, 3 }) {
for (long id : new long[] {0, 3 }) {
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -109,9 +109,9 @@ public class NeuronSquareMesh2DTest {
}
// Neurons 1 and 2.
for (long id : new long[] { 1, 2 }) {
for (long id : new long[] {1, 2 }) {
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -129,7 +129,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test2x2Network2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
2, false,
SquareNeighbourhood.MOORE,
@ -137,9 +137,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours;
// 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));
for (long nId : new long[] { 0, 1, 2, 3 }) {
for (long nId : new long[] {0, 1, 2, 3 }) {
if (id != nId) {
Assert.assertTrue(neighbours.contains(net.getNeuron(nId)));
}
@ -157,7 +157,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x2CylinderNetwork() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -166,7 +166,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -174,7 +174,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -182,7 +182,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -190,7 +190,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -198,7 +198,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -206,7 +206,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -223,7 +223,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x2CylinderNetwork2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(2, false,
3, true,
SquareNeighbourhood.MOORE,
@ -231,9 +231,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours;
// 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));
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) {
Assert.assertTrue("id=" + id + " nId=" + nId,
neighbours.contains(net.getNeuron(nId)));
@ -255,7 +255,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x3TorusNetwork() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, true,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -264,7 +264,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -272,7 +272,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -280,7 +280,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -288,7 +288,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -296,7 +296,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -304,7 +304,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -312,7 +312,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -320,7 +320,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -328,7 +328,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -348,7 +348,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x3TorusNetwork2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, true,
3, true,
SquareNeighbourhood.MOORE,
@ -356,9 +356,9 @@ public class NeuronSquareMesh2DTest {
Collection<Neuron> neighbours;
// 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));
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) {
Assert.assertTrue("id=" + id + " nId=" + nId,
neighbours.contains(net.getNeuron(nId)));
@ -380,7 +380,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x3CylinderNetwork() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, false,
3, true,
SquareNeighbourhood.MOORE,
@ -389,7 +389,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -397,7 +397,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -405,7 +405,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -413,7 +413,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -421,7 +421,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -429,7 +429,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -437,7 +437,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -445,7 +445,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -453,7 +453,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -473,7 +473,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void test3x3CylinderNetwork2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(3, false,
3, false,
SquareNeighbourhood.MOORE,
@ -482,7 +482,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -490,7 +490,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -498,7 +498,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -506,7 +506,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -514,7 +514,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -522,7 +522,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -530,7 +530,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -538,7 +538,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -546,7 +546,7 @@ public class NeuronSquareMesh2DTest {
// Neuron 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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -572,7 +572,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void testConcentricNeighbourhood() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(5, true,
5, true,
SquareNeighbourhood.VON_NEUMANN,
@ -583,7 +583,7 @@ public class NeuronSquareMesh2DTest {
// Level-1 neighbourhood.
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -595,7 +595,7 @@ public class NeuronSquareMesh2DTest {
exclude.addAll(neighbours);
// 3. Retrieve level-2 neighbourhood.
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -621,7 +621,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void testConcentricNeighbourhood2() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final Network net = new NeuronSquareMesh2D(5, true,
5, true,
SquareNeighbourhood.MOORE,
@ -632,7 +632,7 @@ public class NeuronSquareMesh2DTest {
// Level-1 neighbourhood.
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -644,7 +644,7 @@ public class NeuronSquareMesh2DTest {
exclude.addAll(neighbours);
// 3. Retrieve level-2 neighbourhood.
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)));
}
// Ensures that no other neurons is in the neighbourhood set.
@ -655,7 +655,7 @@ public class NeuronSquareMesh2DTest {
public void testSerialize()
throws IOException,
ClassNotFoundException {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D out = new NeuronSquareMesh2D(4, false,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -700,7 +700,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void testGetNeuron() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(2, false,
2, true,
SquareNeighbourhood.VON_NEUMANN,
@ -749,7 +749,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void testGetNeuronAlongDirection() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, false,
3, false,
SquareNeighbourhood.VON_NEUMANN,
@ -810,7 +810,7 @@ public class NeuronSquareMesh2DTest {
*/
@Test
public void testGetNeuronAlongDirectionWrappedMap() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, true,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -854,7 +854,7 @@ public class NeuronSquareMesh2DTest {
@Test
public void testIterator() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true,
3, true,
SquareNeighbourhood.VON_NEUMANN,
@ -880,7 +880,7 @@ public class NeuronSquareMesh2DTest {
@Test
public void testDataVisualization() {
final FeatureInitializer[] initArray = { init };
final FeatureInitializer[] initArray = {init};
final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true,
3, true,
SquareNeighbourhood.VON_NEUMANN,

View File

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

View File

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

View File

@ -135,7 +135,6 @@ public class FastFourierTransform implements ComplexTransform {
throw new TransformException(TransformException.SIZE_MISMATCH,
dataI.length, dataR.length);
}
final int n = dataR.length;
if (!ArithmeticUtils.isPowerOfTwo(n)) {
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).
for (int destEvenStartIndex = 0;
destEvenStartIndex < n;
destEvenStartIndex += n0) {
for (int destEvenStartIndex = 0; destEvenStartIndex < n; destEvenStartIndex += n0) {
final int destOddStartIndex = destEvenStartIndex + lastN0;
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.
*/
@Override
public Complex[] apply(final double[] f) {
final double[][] dataRI = new double[][] {
Arrays.copyOf(f, f.length),

View File

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

View File

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

View File

@ -46,7 +46,7 @@ class TransformException extends IllegalArgumentException {
* @param message Message format (with replaceable parameters).
* @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));
}
}

View File

@ -16,7 +16,6 @@
*/
package org.apache.commons.math4.transform;
import java.util.Arrays;
import java.util.function.DoubleUnaryOperator;
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.
* Class is package-private (for internal use only).
*/
class TransformUtils {
final class TransformUtils {
/** Utility class. */
private TransformUtils() {}

View File

@ -71,7 +71,7 @@ public final class FastCosineTransformerTest
public static Collection<Object[]> data() {
final FastCosineTransform.Norm[] normalization = FastCosineTransform.Norm.values();
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];
}
return Arrays.asList(data);
@ -110,7 +110,7 @@ public final class FastCosineTransformerTest
@Override
DoubleUnaryOperator getValidFunction() {
final UnivariateFunction sinc = new Sinc();
return (x) -> sinc.value(x);
return x -> sinc.value(x);
}
@Override
@ -169,12 +169,13 @@ public final class FastCosineTransformerTest
@Test
public void testAdHocData() {
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
};
final double y[] = {
final double[] y = {
172.0, -105.096569476353, 27.3137084989848, -12.9593152353742,
8.0, -5.78585076868676, 4.68629150101524, -4.15826451958632,
4.0
@ -211,7 +212,7 @@ public final class FastCosineTransformerTest
@Test
public void testParameters() throws Exception {
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);
try {
@ -241,26 +242,26 @@ public final class FastCosineTransformerTest
@Test
public void testSinFunction() {
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);
double min, max, result[], tolerance = 1e-12;
int N = 9;
double tolerance = 1e-12;
int size = 9;
final double expected[] = {
final double[] expected = {
0.0, 3.26197262739567, 0.0, -2.17958042710327, 0.0,
-0.648846697642915, 0.0, -0.433545502649478, 0.0
};
min = 0.0;
max = 2.0 * Math.PI * N / (N - 1);
result = transformer.apply(f, min, max, N);
for (int i = 0; i < N; i++) {
double min = 0.0;
double max = 2.0 * Math.PI * size / (size - 1);
double[] result = transformer.apply(f, min, max, size);
for (int i = 0; i < size; i++) {
Assert.assertEquals(expected[i], result[i], tolerance);
}
min = -Math.PI;
max = Math.PI * (N + 1) / (N - 1);
result = transformer.apply(f, min, max, N);
for (int i = 0; i < N; i++) {
max = Math.PI * (size + 1) / (size - 1);
result = transformer.apply(f, min, max, size);
for (int i = 0; i < size; i++) {
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 {
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. */
private static final UniformRandomProvider RNG = RandomSource.create(RandomSource.MWC_256);
@ -50,7 +50,7 @@ public final class FastFourierTransformerTest {
final Complex[] x = createComplexData(n);
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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);
try {
fft.apply(x);
@ -69,7 +69,7 @@ public final class FastFourierTransformerTest {
final double[] x = createRealData(n);
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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);
try {
fft.apply(x);
@ -87,7 +87,7 @@ public final class FastFourierTransformerTest {
final int n = 127;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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);
try {
fft.apply(SIN, 0.0, Math.PI, n);
@ -105,7 +105,7 @@ public final class FastFourierTransformerTest {
final int n = -128;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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);
try {
fft.apply(SIN, 0.0, Math.PI, n);
@ -124,7 +124,7 @@ public final class FastFourierTransformerTest {
final int n = 128;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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);
try {
fft.apply(SIN, Math.PI, 0.0, n);
@ -195,7 +195,7 @@ public final class FastFourierTransformerTest {
final double s;
if (!inverse) {
expected = dft(x, -1);
if (normalization == FastFourierTransform.Norm.STD){
if (normalization == FastFourierTransform.Norm.STD) {
s = 1.0;
} else {
s = 1.0 / Math.sqrt(n);
@ -309,7 +309,7 @@ public final class FastFourierTransformerTest {
public void testTransformComplex() {
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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(4, 1e-14, norm[i], type);
doTestTransformComplex(8, 1e-13, norm[i], type);
@ -325,7 +325,7 @@ public final class FastFourierTransformerTest {
public void testStandardTransformReal() {
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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(4, 1e-14, norm[i], type);
doTestTransformReal(8, 1e-13, norm[i], type);
@ -340,14 +340,14 @@ public final class FastFourierTransformerTest {
@Test
public void testStandardTransformFunction() {
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 max = Math.PI;
final FastFourierTransform.Norm[] norm = FastFourierTransform.Norm.values();
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, 4, 1e-14, norm[i], type);
doTestTransformFunction(f, min, max, 8, 1e-14, norm[i], type);
@ -367,10 +367,11 @@ public final class FastFourierTransformerTest {
@Test
public void testAdHocData() {
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 Complex y[] = {
final double[] x = {1.3, 2.4, 1.7, 4.1, 2.9, 1.7, 5.1, 2.7};
final Complex[] y = {
Complex.ofCartesian(21.9, 0.0),
Complex.ofCartesian(-2.09497474683058, 1.91507575950825),
Complex.ofCartesian(-2.6, 2.7),
@ -394,9 +395,9 @@ public final class FastFourierTransformerTest {
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));
Complex y2[] = y;
Complex[] y2 = y;
transformer = new FastFourierTransform(FastFourierTransform.Norm.UNIT);
result = transformer.apply(y2);
@ -419,18 +420,19 @@ public final class FastFourierTransformerTest {
@Test
public void testSinFunction() {
FastFourierTransform transformer;
Complex result[]; int N = 1 << 8;
double min, max, tolerance = 1e-12;
Complex[] result;
int size = 1 << 8;
double tolerance = 1e-12;
min = 0.0;
max = 2 * Math.PI;
double min = 0.0;
double max = 2 * Math.PI;
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(-(N >> 1), result[1].getImaginary(), tolerance);
Assert.assertEquals(0.0, result[N-1].getReal(), tolerance);
Assert.assertEquals(N >> 1, result[N-1].getImaginary(), tolerance);
for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) {
Assert.assertEquals(-(size >> 1), result[1].getImaginary(), tolerance);
Assert.assertEquals(0.0, result[size - 1].getReal(), tolerance);
Assert.assertEquals(size >> 1, result[size - 1].getImaginary(), tolerance);
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].getImaginary(), tolerance);
}
@ -438,12 +440,12 @@ public final class FastFourierTransformerTest {
min = -Math.PI;
max = Math.PI;
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.5, result[1].getImaginary(), tolerance);
Assert.assertEquals(0.0, result[N-1].getReal(), tolerance);
Assert.assertEquals(0.5, result[N-1].getImaginary(), tolerance);
for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) {
Assert.assertEquals(0.0, result[size - 1].getReal(), tolerance);
Assert.assertEquals(0.5, result[size - 1].getImaginary(), tolerance);
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].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 {
/**
@ -31,8 +31,8 @@ public final class FastHadamardTransformerTest {
*/
@Test
public void test8Points() {
checkAllTransforms(new int[] { 1, 4, -2, 3, 0, 1, 4, -1 },
new int[] { 10, -4, 2, -4, 2, -12, 6, 8 });
checkAllTransforms(new int[] {1, 4, -2, 3, 0, 1, 4, -1},
new int[] {10, -4, 2, -4, 2, -12, 6, 8});
}
/**
@ -40,8 +40,8 @@ public final class FastHadamardTransformerTest {
*/
@Test
public void test4Points() {
checkAllTransforms(new int[] { 1, 2, 3, 4 },
new int[] { 10, -2, -4, 0 });
checkAllTransforms(new int[] {1, 2, 3, 4},
new int[] {10, -2, -4, 0});
}
/**
@ -50,11 +50,11 @@ public final class FastHadamardTransformerTest {
@Test
public void testNoIntInverse() {
final FastHadamardTransform transformer = new FastHadamardTransform(true);
final double[] x = transformer.apply(new double[] { 0, 1, 0, 1});
Assert.assertEquals( 0.5, x[0], 0);
final double[] x = transformer.apply(new double[] {0, 1, 0, 1});
Assert.assertEquals(0.5, x[0], 0);
Assert.assertEquals(-0.5, x[1], 0);
Assert.assertEquals( 0.0, x[2], 0);
Assert.assertEquals( 0.0, x[3], 0);
Assert.assertEquals(0.0, x[2], 0);
Assert.assertEquals(0.0, x[3], 0);
}
/**
@ -85,7 +85,7 @@ public final class FastHadamardTransformerTest {
for (int i = 0; i < dX.length; ++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++) {
// compare computed results to precomputed results
Assert.assertTrue(Precision.equals(y[i], dResult[i], 1));
@ -97,12 +97,11 @@ public final class FastHadamardTransformerTest {
final FastHadamardTransform transformer = new FastHadamardTransform();
// check integer transform
final int iResult[] = transformer.apply(x);
final int[] iResult = transformer.apply(x);
for (int i = 0; i < iResult.length; i++) {
// compare computed results to precomputed results
Assert.assertEquals(y[i], iResult[i]);
}
}
private void checkInverseDoubleTransform(int[]x, int[] y) {
@ -114,12 +113,10 @@ public final class FastHadamardTransformerTest {
for (int i = 0; i < dY.length; ++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++) {
// compare computed results to precomputed results
Assert.assertTrue(Precision.equals(x[i], dResult[i], 1));
}
}
}

View File

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

View File

@ -20,7 +20,6 @@ import org.junit.Assert;
import org.junit.Test;
import java.util.function.DoubleUnaryOperator;
import org.apache.commons.rng.UniformRandomProvider;
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
* sizes. For each generated data array, actual 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
* expected exceptions.
*
@ -49,7 +48,7 @@ public abstract class RealTransformerAbstractTest {
/**
* 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 <}
* {@link #getNumberOfInvalidDataSizes()}
@ -116,7 +115,7 @@ public abstract class RealTransformerAbstractTest {
/**
* 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
* methods should throw an exception when passed this bound.
*
@ -143,7 +142,7 @@ public abstract class RealTransformerAbstractTest {
public void testTransformRealInvalidDataSize() {
for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) {
final int n = getInvalidDataSize(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
try {
final RealTransform transformer = createRealTransformer(type);
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
* invalid.
*/
@ -167,7 +166,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfInvalidDataSizes(); i++) {
final int n = getInvalidDataSize(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
try {
final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, a, b, n);
@ -191,7 +190,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
try {
final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, a, b, -n);
@ -215,7 +214,7 @@ public abstract class RealTransformerAbstractTest {
final double b = getValidUpperBound();
for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
try {
final RealTransform transformer = createRealTransformer(type);
transformer.apply(f, b, a, n);
@ -245,7 +244,7 @@ public abstract class RealTransformerAbstractTest {
for (int i = 0; i < getNumberOfValidDataSizes(); i++) {
final int n = getValidDataSize(i);
final double tol = getRelativeTolerance(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
doTestTransformReal(n, tol, type);
}
}
@ -253,10 +252,11 @@ public abstract class RealTransformerAbstractTest {
/**
* 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
* {@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
* transform, return by {@link #transform(double[], boolean)}. Actual
* 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++) {
final int n = getValidDataSize(i);
final double tol = getRelativeTolerance(i);
for (boolean type : new boolean[] { true, false }) {
for (boolean type : new boolean[] {true, false}) {
doTestTransformFunction(n, tol, type);
}
}

View File

@ -28,20 +28,20 @@ import org.apache.commons.math3.analysis.function.Sin;
*/
public class TransformUtilsTest {
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)
public void testSampleWrongBounds(){
public void testSampleWrongBounds() {
TransformUtils.sample(SIN, Math.PI, 0.0, 10);
}
@Test(expected = TransformException.class)
public void testSampleNegativeNumberOfPoints(){
public void testSampleNegativeNumberOfPoints() {
TransformUtils.sample(SIN, 0.0, Math.PI, -1);
}
@Test(expected = TransformException.class)
public void testSampleNullNumberOfPoints(){
public void testSampleNullNumberOfPoints() {
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"
"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[/\\].*" />
<suppress checks="HiddenField" files=".*[/\\]examples[/\\]sofm[/\\]tsp[/\\]City\.java" />
<suppress checks="LineLength" files=".*[/\\]LocalizedFormats\.java" />
<suppress checks="FileLength" files=".*[/\\]AccurateMath.*\.java" />
<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>

View File

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