Example usage for org.apache.commons.math3.util FastMath floor

List of usage examples for org.apache.commons.math3.util FastMath floor

Introduction

In this page you can find the example usage for org.apache.commons.math3.util FastMath floor.

Prototype

public static double floor(double x) 

Source Link

Document

Get the largest whole number smaller than x.

Usage

From source file:gentracklets.Propagate.java

public static void main(String[] args) throws OrekitException {

    // load the data files
    File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip");
    DataProvidersManager DM = DataProvidersManager.getInstance();
    ZipJarCrawler crawler = new ZipJarCrawler(data);
    DM.clearProviders();//ww  w.  jav a2s  .c om
    DM.addProvider(crawler);

    // Read in TLE elements
    File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle");
    FileReader TLEfr;
    Vector<TLE> tles = new Vector<>();
    tles.setSize(30);

    try {
        // read and save TLEs to a vector
        TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle");
        BufferedReader readTLE = new BufferedReader(TLEfr);

        Scanner s = new Scanner(tleFile);

        String line1, line2;
        TLE2 tle = new TLE2();

        int nrOfObj = 4;
        for (int ii = 1; ii < nrOfObj + 1; ii++) {
            System.out.println(ii);
            line1 = s.nextLine();
            line2 = s.nextLine();
            if (TLE.isFormatOK(line1, line2)) {
                tles.setElementAt(new TLE(line1, line2), ii);
                System.out.println(tles.get(ii).toString());
            } else {
                System.out.println("format problem");
            }

        }
        readTLE.close();

        // define a groundstation
        Frame inertialFrame = FramesFactory.getEME2000();
        TimeScale utc = TimeScalesFactory.getUTC();
        double longitude = FastMath.toRadians(7.465);
        double latitude = FastMath.toRadians(46.87);
        double altitude = 950.;
        GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);
        TopocentricFrame staF = new TopocentricFrame(earth, station, "station");

        Vector<Orbit> eles = new Vector<>();
        eles.setSize(tles.size());
        for (int ii = 1; ii < nrOfObj + 1; ii++) {
            double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2),
                    (1.0 / 3));
            // convert them to orbits
            Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(),
                    tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(),
                    PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU);

            eles.setElementAt(kep, ii);

            // set up propagators
            KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii));

            System.out.println("a: " + a);

            // Initial state definition
            double mass = 1000.0;
            SpacecraftState initialState = new SpacecraftState(kep, mass);

            // Adaptive step integrator
            // with a minimum step of 0.001 and a maximum step of 1000
            double minStep = 0.001;
            double maxstep = 1000.0;
            double positionTolerance = 10.0;
            OrbitType propagationType = OrbitType.KEPLERIAN;
            double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType);
            AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep,
                    tolerances[0], tolerances[1]);

            NumericalPropagator propagator = new NumericalPropagator(integrator);
            propagator.setOrbitType(propagationType);

            // set up and add force models
            double AMR = 4.0;
            double crossSection = mass * AMR;
            double Cd = 0.01;
            double Cr = 0.5;
            double Co = 0.8;
            NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4);
            ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel(
                    FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);
            SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co);
            PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            SolarRadiationPressure srp = new SolarRadiationPressure(sun,
                    Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc);

            //                propagator.addForceModel(srp);
            //                propagator.addForceModel(holmesFeatherstone);
            propagator.setInitialState(initialState);

            // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets)
            Vector<AbsoluteDate> startDates = new Vector<>();
            startDates.setSize(1);
            startDates.setElementAt(new AbsoluteDate(2016, 1, 26, 20, 00, 00, utc), 0);

            // set the step size [s] and total length
            double tstep = 100;
            double ld = 3;
            double ls = FastMath.floor(ld * (24 * 60 * 60) / tstep);
            System.out.println(ls);

            SpacecraftState currentStateKep = kepler.propagate(startDates.get(0));
            SpacecraftState currentStatePer = propagator.propagate(startDates.get(0));

            for (int tt = 0; tt < startDates.size(); tt++) {

                // set up output file
                String app = tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt";

                // with formatted output
                File file1 = new File("/home/zittersteijn/Documents/propagate/keplerian/MEO/" + app);
                File file2 = new File("/home/zittersteijn/Documents/propagate/perturbed/MEO/" + app);
                file1.createNewFile();
                file2.createNewFile();
                Formatter fmt1 = new Formatter(file1);
                Formatter fmt2 = new Formatter(file2);

                for (int kk = 0; kk < (int) ls; kk++) {
                    AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk);
                    currentStateKep = kepler.propagate(propDate);
                    currentStatePer = propagator.propagate(propDate);

                    System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t"
                            + currentStateKep.getDate());

                    // convert to RADEC coordinates
                    double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF,
                            inertialFrame, propDate);
                    double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF,
                            inertialFrame, propDate);

                    // write the orbit to seperate files with the RA, DEC, epoch and fence given
                    AbsoluteDate year = new AbsoluteDate(YEAR, utc);
                    fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2],
                            (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1));
                    fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2],
                            (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1));

                }
                fmt1.flush();
                fmt1.close();
                fmt2.flush();
                fmt2.close();

            }
            double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame,
                    new AbsoluteDate(startDates.get(0), ls * tstep));
            double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame,
                    new AbsoluteDate(startDates.get(0), ls * tstep));
            double sig0 = 1.0 / 3600.0 / 180.0 * FastMath.PI;
            double dRA = radecKep[0] - radecPer[0] / (sig0 * sig0);
            double dDEC = radecKep[2] - radecPer[2] / (sig0 * sig0);

            System.out.println(dRA + "\t" + dDEC);

        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException iox) {
        Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox);
    }

}

From source file:cloudnet.pm.PmSpecPower.java

@Override
public double getPower(double utilization) throws IllegalArgumentException {
    Ensure.BetweenInclusive(utilization, 0.0, 1.0, "utilization");
    if (utilization % 0.1 == 0) {
        return getPowerData((int) (utilization * 10));
    }/*from w  w w. jav  a 2  s .  c o  m*/
    int utilization1 = (int) FastMath.floor(utilization * 10);
    int utilization2 = (int) FastMath.ceil(utilization * 10);
    double power1 = getPowerData(utilization1);
    double power2 = getPowerData(utilization2);
    double delta = (power2 - power1) / 10;
    double power = power1 + delta * (utilization - (double) utilization1 / 10) * 100;
    return power;
}

From source file:cloudnet.sla.VmSlaOverallDowntime.java

@Override
public double getPenalty() {
    Ensure.NotNull(vm, "vm");
    if (vm.getRequestedRunningTime() == 0L) {
        return 0.0;
    }/*  w w  w .  j  ava  2 s .  c o  m*/

    float percent = (float) vm.getDowntime() / billingPeriod;
    float violations = percent / (float) downtimeViolationStep;
    int violationsCount = (int) FastMath.floor(violations);
    return round(getDowntimePercentPenalty() * violationsCount, 2);
}

From source file:cloudnet.sla.VmSlaOverallDowntime.java

public double getViolationRate() {
    Ensure.NotNull(vm, "vm");
    double percent = (double) vm.getDowntime() / billingPeriod;
    int violationsCount = (int) FastMath.floor(percent / downtimeViolationStep);
    double result = (percent - violationsCount * downtimeViolationStep) / downtimeViolationStep;
    return result;
}

From source file:cc.mallet.types.PolyaUrnDirichlet.java

protected long nextPoisson(double meanPoisson) {
    final double pivot = 40.0d;
    if (meanPoisson < pivot) {
        double p = FastMath.exp(-meanPoisson);
        long n = 0;
        double r = 1.0d;
        double rnd = 1.0d;

        while (n < 1000 * meanPoisson) {
            rnd = ThreadLocalRandom.current().nextDouble();
            r *= rnd;//  w  w w .  j ava2  s  .co m
            if (r >= p) {
                n++;
            } else {
                return n;
            }
        }
        return n;
    } else {
        final double lambda = FastMath.floor(meanPoisson);
        final double lambdaFractional = meanPoisson - lambda;
        final double logLambda = FastMath.log(lambda);
        final double logLambdaFactorial = CombinatoricsUtils.factorialLog((int) lambda);
        final long y2 = lambdaFractional < Double.MIN_VALUE ? 0 : nextPoisson(lambdaFractional);
        final double delta = FastMath.sqrt(lambda * FastMath.log(32 * lambda / FastMath.PI + 1));
        final double halfDelta = delta / 2;
        final double twolpd = 2 * lambda + delta;
        final double a1 = FastMath.sqrt(FastMath.PI * twolpd) * FastMath.exp(1 / (8 * lambda));
        final double a2 = (twolpd / delta) * FastMath.exp(-delta * (1 + delta) / twolpd);
        final double aSum = a1 + a2 + 1;
        final double p1 = a1 / aSum;
        final double p2 = a2 / aSum;
        final double c1 = 1 / (8 * lambda);

        double x = 0;
        double y = 0;
        double v = 0;
        int a = 0;
        double t = 0;
        double qr = 0;
        double qa = 0;
        for (;;) {
            final double u = ThreadLocalRandom.current().nextDouble();
            if (u <= p1) {
                final double n = ThreadLocalRandom.current().nextGaussian();
                x = n * FastMath.sqrt(lambda + halfDelta) - 0.5d;
                if (x > delta || x < -lambda) {
                    continue;
                }
                y = x < 0 ? FastMath.floor(x) : FastMath.ceil(x);
                final double e = nextStandardExponential();
                v = -e - (n * n / 2) + c1;
            } else {
                if (u > p1 + p2) {
                    y = lambda;
                    break;
                } else {
                    x = delta + (twolpd / delta) * nextStandardExponential();
                    y = FastMath.ceil(x);
                    v = -nextStandardExponential() - delta * (x + 1) / twolpd;
                }
            }
            a = x < 0 ? 1 : 0;
            t = y * (y + 1) / (2 * lambda);
            if (v < -t && a == 0) {
                y = lambda + y;
                break;
            }
            qr = t * ((2 * y + 1) / (6 * lambda) - 1);
            qa = qr - (t * t) / (3 * (lambda + a * (y + 1)));
            if (v < qa) {
                y = lambda + y;
                break;
            }
            if (v > qr) {
                continue;
            }
            if (v < y * logLambda - CombinatoricsUtils.factorialLog((int) (y + lambda)) + logLambdaFactorial) {
                y = lambda + y;
                break;
            }
        }
        return y2 + (long) y;
    }
}

From source file:it.unibo.alchemist.modelchecker.AlchemistASMC.java

private static int computeMinimum(final double interval, final double confidence) {
    final UnivariateFunction f = new UnivariateFunction() {
        @Override/*from  ww  w  .  ja v a2s. c om*/
        public double value(final double n) {
            double t;
            if (Math.ceil(n) == FastMath.floor(n)) {
                t = new TDistribution((int) n).inverseCumulativeProbability(1 - confidence / 2);
            } else {
                double t1 = new TDistribution((int) FastMath.ceil(n))
                        .inverseCumulativeProbability((1 - confidence / 2)) * (n - Math.floor(n));
                double t2 = new TDistribution((int) FastMath.floor(n))
                        .inverseCumulativeProbability((1 - confidence / 2)) * (Math.ceil(n) - n);
                t = t1 + t2;
            }
            double value = 2 * t / n;
            return value - interval;
        }
    };
    final BisectionSolver bs = new BisectionSolver();
    return (int) Math.ceil(bs.solve(Integer.MAX_VALUE, f, 1, Integer.MAX_VALUE));
}

From source file:net.myrrix.online.som.SelfOrganizingMaps.java

/**
 * Completes the update step after assigning an input vector tentatively to a {@link Node}. The assignment
 * causes nearby nodes (including the assigned one) to move their centers towards the vector.
 *//*from  ww w  . jav a  2  s.  c o m*/
private void updateNeighborhood(Node[][] map, float[] V, int bmuI, int bmuJ, double decayFactor) {
    int mapSize = map.length;
    double neighborhoodRadius = mapSize * decayFactor;

    int minI = FastMath.max(0, (int) FastMath.floor(bmuI - neighborhoodRadius));
    int maxI = FastMath.min(mapSize, (int) FastMath.ceil(bmuI + neighborhoodRadius));
    int minJ = FastMath.max(0, (int) FastMath.floor(bmuJ - neighborhoodRadius));
    int maxJ = FastMath.min(mapSize, (int) FastMath.ceil(bmuJ + neighborhoodRadius));

    for (int i = minI; i < maxI; i++) {
        Node[] mapRow = map[i];
        for (int j = minJ; j < maxJ; j++) {
            double learningRate = initLearningRate * decayFactor;
            double currentDistance = distance(i, j, bmuI, bmuJ);
            double theta = FastMath.exp(
                    -(currentDistance * currentDistance) / (2.0 * neighborhoodRadius * neighborhoodRadius));
            double learningTheta = learningRate * theta;
            float[] center = mapRow[j].getCenter();
            int length = center.length;
            // Don't synchronize, for performance. Colliding updates once in a while does little.
            for (int k = 0; k < length; k++) {
                center[k] += (float) (learningTheta * (V[k] - center[k]));
            }
        }
    }
}

From source file:cloudnet.examples.elasticity.bn.DistrHelper.java

private static double[] getWorkloadDistrByAverageValue(double time) {

    double[] result = new double[WorkloadLevel.AllWithOverusage().length];
    int index = 0;
    double levelStep = (100.0 / WorkloadLevel.All().length);

    // get percent
    double percent = (100 * time) / (double) MaxSlaViolationTime;
    //specify distr
    NormalDistribution d = new NormalDistribution(percent / 2, percent / 6);

    // get probabilites
    double[] probabilities = new double[WorkloadLevel.AllWithOverusage().length];
    double maxp = 0.0d;
    for (int l = 0; l < WorkloadLevel.AllWithOverusage().length - 1; l++) {
        double p = d.probability(l * levelStep, (l + 1) * levelStep);
        probabilities[l] = p;/*from  www  .  j a  v  a2  s  .c  o  m*/
        maxp = FastMath.max(maxp, p);
    }
    probabilities[WorkloadLevel.AllWithOverusage().length - 1] = d
            .probability(WorkloadLevel.AllWithOverusage().length * levelStep, Double.POSITIVE_INFINITY);

    if (maxp != 0.0d) {

        // and insert their normalized values into result array 
        double sum = 1.0d;
        for (int l = 0; l < probabilities.length - 1; l++) {
            double newValue = FastMath.min(sum, probabilities[l] / maxp);
            result[index++] = newValue;
            sum -= newValue;
        }
        result[index++] = sum;
        Ensure.GreaterThanOrEquals(sum, 0d, "sum of probabilities");
    } else {
        // if no max probability found, just put 1.0 for the closest level
        // let say, if percent = 42 and there are 10 levels, levelIndex = would be 4
        int levelIndex = (int) FastMath.floor(percent / levelStep);
        if (levelIndex > WorkloadLevel.All().length) {
            levelIndex = WorkloadLevel.AllWithOverusage().length - 1;
        }
        Ensure.GreaterThanOrEquals(levelIndex, 0, "levelIndex");
        for (int l = 0; l < WorkloadLevel.AllWithOverusage().length; l++) {
            if (l == levelIndex) {
                result[index++] = 1.0d;
            } else {
                result[index++] = 0.0d;
            }
        }
    }

    return result;
}

From source file:com.ibm.bi.dml.runtime.functionobjects.Builtin.java

public double execute(double in) throws DMLRuntimeException {
    switch (bFunc) {
    case SIN://from ww w.  j  ava2 s . c  om
        return FASTMATH ? FastMath.sin(in) : Math.sin(in);
    case COS:
        return FASTMATH ? FastMath.cos(in) : Math.cos(in);
    case TAN:
        return FASTMATH ? FastMath.tan(in) : Math.tan(in);
    case ASIN:
        return FASTMATH ? FastMath.asin(in) : Math.asin(in);
    case ACOS:
        return FASTMATH ? FastMath.acos(in) : Math.acos(in);
    case ATAN:
        return Math.atan(in); //faster in Math
    case CEIL:
        return FASTMATH ? FastMath.ceil(in) : Math.ceil(in);
    case FLOOR:
        return FASTMATH ? FastMath.floor(in) : Math.floor(in);
    case LOG:
        //if ( in <= 0 )
        //   throw new DMLRuntimeException("Builtin.execute(): logarithm can only be computed for non-negative numbers (input = " + in + ").");
        // for negative numbers, Math.log will return NaN
        return FASTMATH ? FastMath.log(in) : Math.log(in);
    case LOG_NZ:
        return (in == 0) ? 0 : FASTMATH ? FastMath.log(in) : Math.log(in);

    case ABS:
        return Math.abs(in); //no need for FastMath

    case SQRT:
        //if ( in < 0 )
        //   throw new DMLRuntimeException("Builtin.execute(): squareroot can only be computed for non-negative numbers (input = " + in + ").");
        return Math.sqrt(in); //faster in Math

    case PLOGP:
        if (in == 0.0)
            return 0.0;
        else if (in < 0)
            return Double.NaN;
        else
            return (in * (FASTMATH ? FastMath.log(in) : Math.log(in)));

    case EXP:
        return FASTMATH ? FastMath.exp(in) : Math.exp(in);

    case ROUND:
        return Math.round(in); //no need for FastMath

    case SPROP:
        //sample proportion: P*(1-P)
        return in * (1 - in);

    case SIGMOID:
        //sigmoid: 1/(1+exp(-x))
        return FASTMATH ? 1 / (1 + FastMath.exp(-in)) : 1 / (1 + Math.exp(-in));

    case SELP:
        //select positive: x*(x>0)
        return (in > 0) ? in : 0;

    default:
        throw new DMLRuntimeException("Builtin.execute(): Unknown operation: " + bFunc);
    }
}

From source file:de.tuberlin.uebb.jbop.example.DerivativeStructure.java

/**
 * Get the largest whole number smaller than instance.
 * /*  w w w .  j  a v a 2  s  .c o  m*/
 * @return floor(this)
 */
public DerivativeStructure floor() {
    return new DerivativeStructure(compiler.getFreeParameters(), compiler.getOrder(), FastMath.floor(data[0]));
}