org.apache.commons.math3.util.FastMath Java Examples

The following examples show how to use org.apache.commons.math3.util.FastMath. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArrayRealVectorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCosine() {
    final ArrayRealVector v = new ArrayRealVector(new double[] {1, 0, 0});

    double[] wData = new double[] {1, 1, 0};
    RealVector w = new ArrayRealVector(wData);
    Assert.assertEquals(FastMath.sqrt(2) / 2, v.cosine(w), normTolerance);

    wData = new double[] {1, 0, 0};
    w = new ArrayRealVector(wData);
    Assert.assertEquals(1, v.cosine(w), normTolerance);

    wData = new double[] {0, 1, 0};
    w = new ArrayRealVector(wData);
    Assert.assertEquals(0, v.cosine(w), 0);

    wData = new double[] {-1, 0, 0};
    w = new ArrayRealVector(wData);
    Assert.assertEquals(-1, v.cosine(w), normTolerance);
}
 
Example #2
Source File: HarmonicOscillatorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testParametricGradient() {
    final double amplitude = 2;
    final double omega = 3;
    final double phase = 4;
    final HarmonicOscillator.Parametric f = new HarmonicOscillator.Parametric();

    final double x = 1;
    final double[] grad = f.gradient(1, new double[] {amplitude, omega, phase});
    final double xTimesOmegaPlusPhase = omega * x + phase;
    final double a = FastMath.cos(xTimesOmegaPlusPhase);
    Assert.assertEquals(a, grad[0], EPS);
    final double w = -amplitude * x * FastMath.sin(xTimesOmegaPlusPhase);
    Assert.assertEquals(w, grad[1], EPS);
    final double p = -amplitude * FastMath.sin(xTimesOmegaPlusPhase);
    Assert.assertEquals(p, grad[2], EPS);
}
 
Example #3
Source File: EventFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testIncreasingOnly()
    throws DimensionMismatchException, NumberIsTooSmallException,
           MaxCountExceededException, NoBracketingException {
    double e = 1e-15;
    FirstOrderIntegrator integrator;
    integrator = new DormandPrince853Integrator(1.0e-3, 100.0, 1e-7, 1e-7);
    Event allEvents = new Event(true, true);
    integrator.addEventHandler(allEvents, 0.1, e, 1000,
                               new BracketingNthOrderBrentSolver(1.0e-7, 5));
    Event onlyIncreasing = new Event(false, true);
    integrator.addEventHandler(new EventFilter(onlyIncreasing,
                                               FilterType.TRIGGER_ONLY_INCREASING_EVENTS),
                               0.1, e, 100,
                               new BracketingNthOrderBrentSolver(1.0e-7, 5));
    double t0 = 0.5 * FastMath.PI;
    double tEnd = 5.5 * FastMath.PI;
    double[] y = { 0.0, 1.0 };
    Assert.assertEquals(tEnd,
                        integrator.integrate(new SineCosine(), t0, y, tEnd, y),
                        1.0e-7);

    Assert.assertEquals(5, allEvents.getEventCount());
    Assert.assertEquals(2, onlyIncreasing.getEventCount());

}
 
Example #4
Source File: ListUnivariateImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public double[] getValues() {

    int length = list.size();

    // If the window size is not INFINITE_WINDOW AND
    // the current list is larger that the window size, we need to
    // take into account only the last n elements of the list
    // as definied by windowSize

    final int wSize = getWindowSize();
    if (wSize != DescriptiveStatistics.INFINITE_WINDOW && wSize < list.size()) {
        length = list.size() - FastMath.max(0, list.size() - wSize);
    }

    // Create an array to hold all values
    double[] copiedArray = new double[length];

    for (int i = 0; i < copiedArray.length; i++) {
        copiedArray[i] = getElement(i);
    }
    return copiedArray;
}
 
Example #5
Source File: FuzzyKMeansClusterer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the value of the objective function.
 * @return the objective function evaluation as double value
 * @throws MathIllegalStateException if {@link #cluster(Collection)} has not been called before
 */
public double getObjectiveFunctionValue() {
    if (points == null || clusters == null) {
        throw new MathIllegalStateException();
    }

    int i = 0;
    double objFunction = 0.0;
    for (final T point : points) {
        int j = 0;
        for (final CentroidCluster<T> cluster : clusters) {
            final double dist = distance(point, cluster.getCenter());
            objFunction += (dist * dist) * FastMath.pow(membershipMatrix[i][j], fuzziness);
            j++;
        }
        i++;
    }
    return objFunction;
}
 
Example #6
Source File: AbstractRealMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public double getFrobeniusNorm() {
    return walkInOptimizedOrder(new RealMatrixPreservingVisitor() {

        /** Sum of squared entries. */
        private double sum;

        /** {@inheritDoc} */
        public void start(final int rows, final int columns,
                          final int startRow, final int endRow,
                          final int startColumn, final int endColumn) {
            sum = 0;
        }

        /** {@inheritDoc} */
        public void visit(final int row, final int column, final double value) {
            sum += value * value;
        }

        /** {@inheritDoc} */
        public double end() {
            return FastMath.sqrt(sum);
        }
    });
}
 
Example #7
Source File: HarmonicFitterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNoError() {
    final double a = 0.2;
    final double w = 3.4;
    final double p = 4.1;
    HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    HarmonicFitter fitter =
        new HarmonicFitter(new LevenbergMarquardtOptimizer());
    for (double x = 0.0; x < 1.3; x += 0.01) {
        fitter.addObservedPoint(1, x, f.value(x));
    }

    final double[] fitted = fitter.fit();
    Assert.assertEquals(a, fitted[0], 1.0e-13);
    Assert.assertEquals(w, fitted[1], 1.0e-13);
    Assert.assertEquals(p, MathUtils.normalizeAngle(fitted[2], p), 1e-13);

    HarmonicOscillator ff = new HarmonicOscillator(fitted[0], fitted[1], fitted[2]);

    for (double x = -1.0; x < 1.0; x += 0.01) {
        Assert.assertTrue(FastMath.abs(f.value(x) - ff.value(x)) < 1e-13);
    }
}
 
Example #8
Source File: DSCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Perform remainder of two derivative structures.
 * @param lhs array holding left hand side of remainder
 * @param lhsOffset offset of the left hand side in its array
 * @param rhs array right hand side of remainder
 * @param rhsOffset offset of the right hand side in its array
 * @param result array where result must be stored (it may be
 * one of the input arrays)
 * @param resultOffset offset of the result in its array
 */
public void remainder(final double[] lhs, final int lhsOffset,
                      final double[] rhs, final int rhsOffset,
                      final double[] result, final int resultOffset) {

    // compute k such that lhs % rhs = lhs - k rhs
    final double rem = FastMath.IEEEremainder(lhs[lhsOffset], rhs[rhsOffset]);
    final double k   = FastMath.rint((lhs[lhsOffset] - rem) / rhs[rhsOffset]);

    // set up value
    result[resultOffset] = rem;

    // set up partial derivatives
    for (int i = 1; i < getSize(); ++i) {
        result[resultOffset + i] = lhs[lhsOffset + i] - k * rhs[rhsOffset + i];
    }

}
 
Example #9
Source File: PolynomialFitterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSmallError() {
    Random randomizer = new Random(53882150042l);
    double maxError = 0;
    for (int degree = 0; degree < 10; ++degree) {
        PolynomialFunction p = buildRandomPolynomial(degree, randomizer);

        PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer());
        for (double x = -1.0; x < 1.0; x += 0.01) {
            fitter.addObservedPoint(1.0, x,
                                    p.value(x) + 0.1 * randomizer.nextGaussian());
        }

        final double[] init = new double[degree + 1];
        PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init));

        for (double x = -1.0; x < 1.0; x += 0.01) {
            double error = FastMath.abs(p.value(x) - fitted.value(x)) /
                          (1.0 + FastMath.abs(p.value(x)));
            maxError = FastMath.max(maxError, error);
            Assert.assertTrue(FastMath.abs(error) < 0.1);
        }
    }
    Assert.assertTrue(maxError > 0.01);
}
 
Example #10
Source File: PolynomialsUtilsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testHighDegreeLegendre() {
    PolynomialsUtils.createLegendrePolynomial(40);
    double[] l40 = PolynomialsUtils.createLegendrePolynomial(40).getCoefficients();
    double denominator = 274877906944d;
    double[] numerators = new double[] {
                      +34461632205d,            -28258538408100d,          +3847870979902950d,        -207785032914759300d,
              +5929294332103310025d,     -103301483474866556880d,    +1197358103913226000200d,    -9763073770369381232400d,
          +58171647881784229843050d,  -260061484647976556945400d,  +888315281771246239250340d, -2345767627188139419665400d,
        +4819022625419112503443050d, -7710436200670580005508880d, +9566652323054238154983240d, -9104813935044723209570256d,
        +6516550296251767619752905d, -3391858621221953912598660d, +1211378079007840683070950d,  -265365894974690562152100d,
          +26876802183334044115405d
    };
    for (int i = 0; i < l40.length; ++i) {
        if (i % 2 == 0) {
            double ci = numerators[i / 2] / denominator;
            Assert.assertEquals(ci, l40[i], FastMath.abs(ci) * 1e-15);
        } else {
            Assert.assertEquals(0, l40[i], 0);
        }
    }
}
 
Example #11
Source File: Line.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Reset the instance as if built from two points.
 * <p>The line is oriented from p1 to p2</p>
 * @param p1 first point
 * @param p2 second point
 */
public void reset(final Vector2D p1, final Vector2D p2) {
    final double dx = p2.getX() - p1.getX();
    final double dy = p2.getY() - p1.getY();
    final double d = FastMath.hypot(dx, dy);
    if (d == 0.0) {
        angle        = 0.0;
        cos          = 1.0;
        sin          = 0.0;
        originOffset = p1.getY();
    } else {
        angle        = FastMath.PI + FastMath.atan2(-dy, -dx);
        cos          = FastMath.cos(angle);
        sin          = FastMath.sin(angle);
        originOffset = (p2.getX() * p1.getY() - p1.getX() * p2.getY()) / d;
    }
}
 
Example #12
Source File: PoissonDistribution.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new Poisson distribution with specified mean, convergence
 * criterion and maximum number of iterations.
 *
 * @param rng Random number generator.
 * @param p Poisson mean.
 * @param epsilon Convergence criterion for cumulative probabilities.
 * @param maxIterations the maximum number of iterations for cumulative
 * probabilities.
 * @throws NotStrictlyPositiveException if {@code p <= 0}.
 * @since 3.1
 */
public PoissonDistribution(RandomGenerator rng,
                           double p,
                           double epsilon,
                           int maxIterations)
throws NotStrictlyPositiveException {
    super(rng);

    if (p <= 0) {
        throw new NotStrictlyPositiveException(LocalizedFormats.MEAN, p);
    }
    mean = p;
    this.epsilon = epsilon;
    this.maxIterations = maxIterations;

    // Use the same RNG instance as the parent class.
    normal = new NormalDistribution(rng, p, FastMath.sqrt(p),
                                    NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    exponential = new ExponentialDistribution(rng, 1,
                                              ExponentialDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
}
 
Example #13
Source File: MinpackTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public double[] computeValue(double[] variables) {
    double x1 = variables[0];
    double x2 = variables[1];
    double x3 = variables[2];
    double tmp1;
    if (x1 == 0) {
        tmp1 = (x2 >= 0) ? 0.25 : -0.25;
    } else {
        tmp1 = FastMath.atan(x2 / x1) / twoPi;
        if (x1 < 0) {
            tmp1 += 0.5;
        }
    }
    double tmp2 = FastMath.sqrt(x1 * x1 + x2 * x2);
    return new double[] {
        10.0 * (x3 - 10 * tmp1),
        10.0 * (tmp2 - 1),
        x3
    };
}
 
Example #14
Source File: BlockRealMatrix.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a data array in blocks layout.
 * <p>
 * This method can be used to create the array argument of the {@link
 * #BlockRealMatrix(int, int, double[][], boolean)} constructor.
 * </p>
 * @param rows Number of rows in the new matrix.
 * @param columns Number of columns in the new matrix.
 * @return a new data array in blocks layout.
 * @see #toBlocksLayout(double[][])
 * @see #BlockRealMatrix(int, int, double[][], boolean)
 */
public static double[][] createBlocksLayout(final int rows, final int columns) {
    final int blockRows = (rows    + BLOCK_SIZE - 1) / BLOCK_SIZE;
    final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;

    final double[][] blocks = new double[blockRows * blockColumns][];
    int blockIndex = 0;
    for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
        final int pStart = iBlock * BLOCK_SIZE;
        final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
        final int iHeight = pEnd - pStart;
        for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
            final int qStart = jBlock * BLOCK_SIZE;
            final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
            final int jWidth = qEnd - qStart;
            blocks[blockIndex] = new double[iHeight * jWidth];
            ++blockIndex;
        }
    }

    return blocks;
}
 
Example #15
Source File: LineTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLineDistance() throws MathIllegalArgumentException {
    Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
    Assert.assertEquals(1.0,
                        l.distance(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))),
                        1.0e-10);
    Assert.assertEquals(0.5,
                        l.distance(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))),
                        1.0e-10);
    Assert.assertEquals(0.0,
                        l.distance(l),
                        1.0e-10);
    Assert.assertEquals(0.0,
                        l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))),
                        1.0e-10);
    Assert.assertEquals(0.0,
                        l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))),
                        1.0e-10);
    Assert.assertEquals(0.0,
                        l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))),
                        1.0e-10);
    Assert.assertEquals(FastMath.sqrt(8),
                        l.distance(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))),
                        1.0e-10);
}
 
Example #16
Source File: LegendreGaussIntegratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSinFunction() {
    UnivariateFunction f = new Sin();
    BaseAbstractUnivariateIntegrator integrator = new LegendreGaussIntegrator(5, 1.0e-14, 1.0e-10, 2, 15);
    double min, max, expected, result, tolerance;

    min = 0; max = FastMath.PI; expected = 2;
    tolerance = FastMath.max(integrator.getAbsoluteAccuracy(),
                         FastMath.abs(expected * integrator.getRelativeAccuracy()));
    result = integrator.integrate(10000, f, min, max);
    Assert.assertEquals(expected, result, tolerance);

    min = -FastMath.PI/3; max = 0; expected = -0.5;
    tolerance = FastMath.max(integrator.getAbsoluteAccuracy(),
            FastMath.abs(expected * integrator.getRelativeAccuracy()));
    result = integrator.integrate(10000, f, min, max);
    Assert.assertEquals(expected, result, tolerance);
}
 
Example #17
Source File: AntlrParserTrigonometricTest.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void acoshNegative() {
	try {
		Expression expression = getExpressionWithFunctionContext("acosh(-10)");
		assertEquals(ExpressionType.DOUBLE, expression.getExpressionType());
		assertEquals(FastMath.acosh(-10), expression.evaluateNumerical(), 1e-15);
	} catch (ExpressionException e) {
		assertNotNull(e.getMessage());
	}
}
 
Example #18
Source File: MultivariateNormalDistribution.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double density(final double[] vals) throws DimensionMismatchException {
    final int dim = getDimension();
    if (vals.length != dim) {
        throw new DimensionMismatchException(vals.length, dim);
    }

    return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *
        FastMath.pow(covarianceMatrixDeterminant, -0.5) *
        getExponentTerm(vals);
}
 
Example #19
Source File: MultivariateSummaryStatistics.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array whose i<sup>th</sup> entry is the standard deviation of the
 * i<sup>th</sup> entries of the arrays that have been added using
 * {@link #addValue(double[])}
 *
 * @return the array of component standard deviations
 */
public double[] getStandardDeviation() {
    double[] stdDev = new double[k];
    if (getN() < 1) {
        Arrays.fill(stdDev, Double.NaN);
    } else if (getN() < 2) {
        Arrays.fill(stdDev, 0.0);
    } else {
        RealMatrix matrix = covarianceImpl.getResult();
        for (int i = 0; i < k; ++i) {
            stdDev[i] = FastMath.sqrt(matrix.getEntry(i, i));
        }
    }
    return stdDev;
}
 
Example #20
Source File: MeanShift.java    From clust4j with Apache License 2.0 5 votes vote down vote up
SerialCenterIntensity(RadiusNeighbors nbrs) {
	
	LogTimer timer;
	
	// Now get single seed members
	MeanShiftSeed sd;
	this.computedSeeds = new TreeSet<>();
	final double[][] X = data.getData();
	
	int idx = 0;
	for(double[] seed: seeds) {
		idx++;
		timer = new LogTimer();
		sd = singleSeed(seed, nbrs, X, maxIter);
		
		if(null == sd)
			continue;
		
		computedSeeds.add(sd);
		itrz = FastMath.max(itrz, sd.iterations);
		
		// If it actually converged, add the summary
		summaries.add(new SummaryLite(
			"Kernel "+(idx - 1), sd.iterations, 
			timer.formatTime(), timer.wallTime()
		));
	}
}
 
Example #21
Source File: CMAESOptimizerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public double value(double[] x) {
    double f = 0;
    double res2 = 0;
    double fac = 0;
    for (int i = 0; i < x.length; ++i) {
        fac = FastMath.pow(axisratio, (i - 1.) / (x.length - 1.));
        f += fac * fac * x[i] * x[i];
        res2 += FastMath.cos(2. * FastMath.PI * fac * x[i]);
    }
    f = (20. - 20. * FastMath.exp(-0.2 * FastMath.sqrt(f / x.length))
            + FastMath.exp(1.) - FastMath.exp(res2 / x.length));
    return f;
}
 
Example #22
Source File: PolyhedronsSetTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testTetrahedron() throws MathArithmeticException {
    Vector3D vertex1 = new Vector3D(1, 2, 3);
    Vector3D vertex2 = new Vector3D(2, 2, 4);
    Vector3D vertex3 = new Vector3D(2, 3, 3);
    Vector3D vertex4 = new Vector3D(1, 3, 4);
    @SuppressWarnings("unchecked")
    PolyhedronsSet tree =
        (PolyhedronsSet) new RegionFactory<Euclidean3D>().buildConvex(
            new Plane(vertex3, vertex2, vertex1, 1.0e-10),
            new Plane(vertex2, vertex3, vertex4, 1.0e-10),
            new Plane(vertex4, vertex3, vertex1, 1.0e-10),
            new Plane(vertex1, vertex2, vertex4, 1.0e-10));
    Assert.assertEquals(1.0 / 3.0, tree.getSize(), 1.0e-10);
    Assert.assertEquals(2.0 * FastMath.sqrt(3.0), tree.getBoundarySize(), 1.0e-10);
    Vector3D barycenter = (Vector3D) tree.getBarycenter();
    Assert.assertEquals(1.5, barycenter.getX(), 1.0e-10);
    Assert.assertEquals(2.5, barycenter.getY(), 1.0e-10);
    Assert.assertEquals(3.5, barycenter.getZ(), 1.0e-10);
    double third = 1.0 / 3.0;
    checkPoints(Region.Location.BOUNDARY, tree, new Vector3D[] {
        vertex1, vertex2, vertex3, vertex4,
        new Vector3D(third, vertex1, third, vertex2, third, vertex3),
        new Vector3D(third, vertex2, third, vertex3, third, vertex4),
        new Vector3D(third, vertex3, third, vertex4, third, vertex1),
        new Vector3D(third, vertex4, third, vertex1, third, vertex2)
    });
    checkPoints(Region.Location.OUTSIDE, tree, new Vector3D[] {
        new Vector3D(1, 2, 4),
        new Vector3D(2, 2, 3),
        new Vector3D(2, 3, 4),
        new Vector3D(1, 3, 3)
    });
}
 
Example #23
Source File: HarmonicOscillatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testDerivative() {
    final double a = -1.2;
    final double w = 0.34;
    final double p = 5.6;
    final HarmonicOscillator f = new HarmonicOscillator(a, w, p);

    for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
        final double d = 0.12345;
        for (int i = 0; i < 10; i++) {
            final double v = i * d;
            final DerivativeStructure h = f.value(new DerivativeStructure(1, maxOrder, 0, v));
            for (int k = 0; k <= maxOrder; ++k) {
                final double trigo;
                switch (k % 4) {
                    case 0:
                        trigo = +FastMath.cos(w * v + p);
                        break;
                    case 1:
                        trigo = -FastMath.sin(w * v + p);
                        break;
                    case 2:
                        trigo = -FastMath.cos(w * v + p);
                        break;
                    default:
                        trigo = +FastMath.sin(w * v + p);
                        break;
                }
                Assert.assertEquals(a * FastMath.pow(w, k) * trigo,
                                    h.getPartialDerivative(k),
                                    Precision.EPSILON);
            }
        }
    }
}
 
Example #24
Source File: ArrayRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public double getL1Norm() {
    double sum = 0;
    for (double a : data) {
        sum += FastMath.abs(a);
    }
    return sum;
}
 
Example #25
Source File: Math_9_Line_t.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from two points.
 * @param p1 first point belonging to the line (this can be any point)
 * @param p2 second point belonging to the line (this can be any point, different from p1)
 * @exception MathIllegalArgumentException if the points are equal
 */
public void reset(final Vector3D p1, final Vector3D p2) throws MathIllegalArgumentException {
    final Vector3D delta = p2.subtract(p1);
    final double norm2 = delta.getNormSq();
    if (norm2 == 0.0) {
        throw new MathIllegalArgumentException(LocalizedFormats.ZERO_NORM);
    }
    this.direction = new Vector3D(1.0 / FastMath.sqrt(norm2), delta);
    zero = new Vector3D(1.0, p1, -p1.dotProduct(delta) / norm2, delta);
}
 
Example #26
Source File: RandomCirclePointGenerator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create one point.
 *
 * @return a point.
 */
private Vector2D create() {
    final double t = tP.sample();
    final double pX = cX.sample() + radius * FastMath.cos(t);
    final double pY = cY.sample() + radius * FastMath.sin(t);

    return new Vector2D(pX, pY);
}
 
Example #27
Source File: Kurtosis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the kurtosis of the entries in the specified portion of the
 * input array.
 * <p>
 * See {@link Kurtosis} for details on the computing algorithm.</p>
 * <p>
 * Throws <code>IllegalArgumentException</code> if the array is null.</p>
 *
 * @param values the input array
 * @param begin index of the first array element to include
 * @param length the number of elements to include
 * @return the kurtosis of the values or Double.NaN if length is less than
 * 4
 * @throws IllegalArgumentException if the input array is null or the array
 * index parameters are not valid
 */
@Override
public double evaluate(final double[] values,final int begin, final int length) {
    // Initialize the kurtosis
    double kurt = Double.NaN;

    if (test(values, begin, length) && length > 3) {

        // Compute the mean and standard deviation
        Variance variance = new Variance();
        variance.incrementAll(values, begin, length);
        double mean = variance.moment.m1;
        double stdDev = FastMath.sqrt(variance.getResult());

        // Sum the ^4 of the distance from the mean divided by the
        // standard deviation
        double accum3 = 0.0;
        for (int i = begin; i < begin + length; i++) {
            accum3 += FastMath.pow(values[i] - mean, 4.0);
        }
        accum3 /= FastMath.pow(stdDev, 4.0d);

        // Get N
        double n0 = length;

        double coefficientOne =
            (n0 * (n0 + 1)) / ((n0 - 1) * (n0 - 2) * (n0 - 3));
        double termTwo =
            (3 * FastMath.pow(n0 - 1, 2.0)) / ((n0 - 2) * (n0 - 3));

        // Calculate kurtosis
        kurt = (coefficientOne * accum3) - termTwo;
    }
    return kurt;
}
 
Example #28
Source File: ErfTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testErf2576() {
    double x = 2.576 / FastMath.sqrt(2.0);
    double actual = Erf.erf(x);
    double expected = 0.99;
    Assert.assertEquals(expected, actual, 1.0e-5);
    Assert.assertEquals(1 - actual, Erf.erfc(x), 1e-15);

    actual = Erf.erf(-x);
    expected = -expected;
    Assert.assertEquals(expected, actual, 1.0e-5);
    Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15);
}
 
Example #29
Source File: NPEfix_00166_s.java    From coming with MIT License 5 votes vote down vote up
/** Reset the instance as if built from a line and an angle.
 * @param p point belonging to the line
 * @param alpha angle of the line with respect to abscissa axis
 */
public void reset(final Vector2D p, final double alpha) {
    this.angle   = MathUtils.normalizeAngle(alpha, FastMath.PI);
    cos          = FastMath.cos(this.angle);
    sin          = FastMath.sin(this.angle);
    originOffset = cos * p.getY() - sin * p.getX();
}
 
Example #30
Source File: Step.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private double[] calculatePerformance() {
	double[] result = new double[3];
	//flops = (20.0f * (double) N * (double) (N - 1) * (double) steps) / 1000000000.0f / getTotalTime();
	// 20 floating point operations
	// 14 to calculate acceleration
	// 6 for velocity and position
	// flops
	double totalTime = getTotalTime();
	System.out.println("calculatePerformance " + size);
	System.out.println("Gflops" + (((14.0*size*size + 6.0*size) * steps)/ 1.0e9 / totalTime));
	System.out.println("Mflops " + (((14.0*size*size + 6.0*size) * steps)/ 1.0e6 / totalTime));
	result[0] = ((14.0*size*size + 6.0*size) * stepsCnt)/ 1.0e9 / totalTime;
	// We calculated the mem size from the bumber of cuboids and their individual size
	//bytes = (4.0f * (double) N * 10.0f * (double) steps)/ 1000000000.0f / getTotalTime();
	result[1] = memSize / 1.0e6 / totalTime;
	// Verify solution.
	result[2] = 0.0f;
	for (NBody3DBody body1 : allBodies) {
		for (NBody3DBody body2 : allBodies) {
			Vector3D distance = body2.position().subtract(body1.position());
			double r2 = FastMath.sqrt(distance.normSq() + eps);
			double r2inv = 1.0 / r2;
			double r6inv = r2inv * r2inv * r2inv;
			result[2] += body2.mass() * r6inv;

		}
	}
	return result;
}