Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

In this page you can find the example usage for java.lang Math floor.

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:com.bc.jexp.impl.DefaultNamespace.java

private void registerDefaultFunctions() {
    registerFunction(new AbstractFunction.D("sin", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.sin(args[0].evalD(env));
        }/*from   w ww  .ja  v a2 s.  c o  m*/
    });
    registerFunction(new AbstractFunction.D("cos", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.cos(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("tan", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.tan(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("asin", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.asin(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("acos", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.acos(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("atan", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.atan(args[0].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("atan2", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.atan2(args[0].evalD(env), args[1].evalD(env));
        }
    });
    registerFunction(new AbstractFunction.D("log", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.log(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("log10", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.log10(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("exp", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.exp(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("exp10", 1) {

        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return FastMath.pow(10.0, args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("sqr", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double v = args[0].evalD(env);
            return v * v;
        }
    });

    registerFunction(new AbstractFunction.D("sqrt", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.sqrt(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("pow", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return FastMath.pow(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("min", 2) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.min(args[0].evalI(env), args[1].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("min", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.min(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("max", 2) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.max(args[0].evalI(env), args[1].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("max", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.max(args[0].evalD(env), args[1].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("floor", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.floor(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("round", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.round(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("ceil", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.ceil(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("rint", 1) {
        public double evalD(EvalEnv env, Term[] args) throws EvalException {
            return Math.rint(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("sign", 1) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return ExtMath.sign(args[0].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("sign", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return ExtMath.sign(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.I("abs", 1) {

        public int evalI(final EvalEnv env, final Term[] args) {
            return Math.abs(args[0].evalI(env));
        }
    });

    registerFunction(new AbstractFunction.D("abs", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.abs(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("deg", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.toDegrees(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("rad", 1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            return Math.toRadians(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("ampl", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            final double a = args[0].evalD(env);
            final double b = args[1].evalD(env);
            return Math.sqrt(a * a + b * b);
        }
    });

    registerFunction(new AbstractFunction.D("phase", 2) {

        public double evalD(final EvalEnv env, final Term[] args) {
            final double a = args[0].evalD(env);
            final double b = args[1].evalD(env);
            return Math.atan2(b, a);
        }
    });

    registerFunction(new AbstractFunction.B("feq", 2) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            return ExtMath.feq(x1, x2, EPS);
        }
    });

    registerFunction(new AbstractFunction.B("feq", 3) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            final double eps = args[2].evalD(env);
            return ExtMath.feq(x1, x2, eps);
        }
    });

    registerFunction(new AbstractFunction.B("fneq", 2) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            return ExtMath.fneq(x1, x2, EPS);
        }
    });

    registerFunction(new AbstractFunction.B("fneq", 3) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            final double x1 = args[0].evalD(env);
            final double x2 = args[1].evalD(env);
            final double eps = args[2].evalD(env);
            return ExtMath.fneq(x1, x2, eps);
        }
    });

    registerFunction(new AbstractFunction.B("inf", 1) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            return Double.isInfinite(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.B("nan", 1) {
        public boolean evalB(EvalEnv env, Term[] args) throws EvalException {
            return Double.isNaN(args[0].evalD(env));
        }
    });

    registerFunction(new AbstractFunction.D("distance", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n; i++) {
                final double v = args[i + n].evalD(env) - args[i].evalD(env);
                sqrSum += v * v;
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.D("distance_deriv", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n - 1; i++) {
                final double v1 = args[i + 1].evalD(env) - args[i].evalD(env);
                final double v2 = args[i + n + 1].evalD(env) - args[i + n].evalD(env);
                sqrSum += (v1 - v2) * (v1 - v2);
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.D("distance_integ", -1) {

        public double evalD(final EvalEnv env, final Term[] args) {
            double sqrSum = 0.0;
            double v1Sum = 0.0;
            double v2Sum = 0.0;
            final int n = args.length / 2;
            for (int i = 0; i < n; i++) {
                v1Sum += args[i].evalD(env);
                v2Sum += args[i + n].evalD(env);
                sqrSum += (v2Sum - v1Sum) * (v2Sum - v1Sum);
            }
            return Math.sqrt(sqrSum);
        }
    });

    registerFunction(new AbstractFunction.B("inrange", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = n1 + args.length / 3;
            for (int i = 0; i < n1; i++) {
                final double v = args[i].evalD(env);
                final double v1 = args[i + n1].evalD(env);
                final double v2 = args[i + n2].evalD(env);
                if (v < v1 || v > v2) {
                    return false;
                }
            }
            return true;
        }
    });

    registerFunction(new AbstractFunction.B("inrange_deriv", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = 2 * n1;
            for (int i = 0; i < n1 - 1; i++) {
                final double v = args[i + 1].evalD(env) - args[i].evalD(env);
                final double v1 = args[i + n1 + 1].evalD(env) - args[i + n1].evalD(env);
                final double v2 = args[i + n2 + 1].evalD(env) - args[i + n2].evalD(env);
                if (v < v1 || v > v2) {
                    return false;
                }
            }
            return true;
        }
    });

    registerFunction(new AbstractFunction.B("inrange_integ", -1) {

        public boolean evalB(final EvalEnv env, final Term[] args) {
            final int n1 = args.length / 3;
            final int n2 = 2 * n1;
            double vSum = 0.0;
            double v1Sum = 0.0;
            double v2Sum = 0.0;
            for (int i = 0; i < n1; i++) {
                vSum += args[i].evalD(env);
                v1Sum += args[i + n1].evalD(env);
                v2Sum += args[i + n2].evalD(env);
                if (vSum < v1Sum || vSum > v2Sum) {
                    return false;
                }
            }
            return true;
        }
    });

}

From source file:com.wordpress.growworkinghard.riverNe3.composite.key.Key.java

/**
 * @brief <strong>decimal</strong> to <strong>hexadecimal</strong> format
 *
 * @description The algorithm has been modified from the original version in
 *              <A HREF=//from  www .ja  v  a  2  s. c om
 *              "http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html">
 *              Introduction to Programming in Java</A>, in order to work
 *              with <code>double</code> data type
 *
 * @param decimalVal The decimal value to convert in hexadecimal
 * @return The hexadecimal format of the input value
 */
private String decimalToHex(double decimalVal) {

    final String DIGITS = "0123456789abcdef";

    if (decimalVal == 0.0)
        return "0";

    String hexadecimal = "";
    while (Math.floor(decimalVal) > 0) {
        int digit = (int) decimalVal % 16;
        hexadecimal = DIGITS.charAt(digit) + hexadecimal;
        decimalVal = decimalVal / 16;
    }

    return hexadecimal;

}

From source file:org.jasig.cas.web.report.StatisticsController.java

/**
 * Calculates the up time./*from w  ww  . jav a2 s  . c  o m*/
 *
 * @param difference the difference
 * @param calculations the calculations
 * @param labels the labels
 * @return the uptime as a string.
 */
protected String calculateUptime(final double difference, final Queue<Integer> calculations,
        final Queue<String> labels) {
    if (calculations.isEmpty()) {
        return "";
    }

    final int value = calculations.remove();
    final double time = Math.floor(difference / value);
    final double newDifference = difference - time * value;
    final String currentLabel = labels.remove();
    final String label = time == 0 || time > 1 ? currentLabel + 's' : currentLabel;

    return Integer.toString((int) time) + ' ' + label + ' '
            + calculateUptime(newDifference, calculations, labels);
}

From source file:com.f16gaming.pathofexilestatistics.MainActivity.java

/**
 * Gets the list offset relative to list start entry.
 * @return The zero-based offset relative to the start entry on the list.
 *///from w w  w.j a  v  a 2  s .  c o m
private int getRelativeOffset() {
    return (int) Math.floor((double) poeEntries.size() / (double) limit) - 1;
}

From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.ClearingGiltsBondsAndCommercialLoansMarket.java

/**
  * Assign commerical loan consumers to risk grades according
  * to their equity. In this implementation, the number of 
  * consumer assigned to each bucket is approximately equal.
  *///from  www. ja  va 2  s .co m
private void assignCommericalLoanClientsToRiskBuckets() {
    final int numRiskBuckets = commercialLoanRiskGrades.size();
    final List<ClearingMarketParticipant> firms = getAllPossibleCommericalLoanConsumers();

    class SortedEquityID implements Comparable<SortedEquityID> {
        private double equity;
        private ClearingMarketParticipant firm;

        SortedEquityID(final double equity, final ClearingMarketParticipant firm) {
            this.equity = equity;
            this.firm = firm;
        }

        @Override
        public int compareTo(SortedEquityID other) {
            return Double.compare(this.equity, other.equity);
        }
    }

    final TreeMultiset<SortedEquityID> firmEquities = TreeMultiset.create();
    for (final ClearingMarketParticipant participant : firms) {
        final LoanStrategyFirm firm = (LoanStrategyFirm) participant; // Contracted by ClearingHouse
        firmEquities.add(new SortedEquityID(firm.getEquity(), participant));
    }
    final int numFirms = firms.size(),
            firmsPerRiskBucket = (int) Math.floor(numFirms / (double) numRiskBuckets);
    int firmCounter = 0, riskGradeIndex = 0;
    String riskGrade = commercialLoanRiskGrades.get(0);
    for (final SortedEquityID record : firmEquities) {
        commericalLoanClientRiskBuckets.get(riskGrade).add(record.firm);
        ++firmCounter;
        if (firmCounter == firmsPerRiskBucket && !(riskGradeIndex == numRiskBuckets - 1)) {
            firmCounter = 0;
            ++riskGradeIndex;
            riskGrade = commercialLoanRiskGrades.get(riskGradeIndex);
        }
    }
    return;
}

From source file:com.krayzk9s.imgurholo.services.UploadService.java

private static Bitmap lessResolution(String filePath, int width, int height) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    // First decode with inJustDecodeBounds=true to check dimensions
    options.inPurgeable = true;//from ww w. ja va  2 s  .  c om
    options.inInputShareable = true;
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);
    BitmapFactory.decodeFile(filePath, options);
    float factor = calculateFactor(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return Bitmap.createScaledBitmap(BitmapFactory.decodeFile(filePath, options),
            (int) Math.floor(options.outWidth * factor), (int) Math.floor(options.outHeight * factor), false);
}

From source file:eu.crisis_economics.abm.firm.TestExogenousFirm.java

/**
  * Test whether an instance of {@link ExogenousFirm} behaves as expected. This
  * test operates as follows:<br><br>
  * //from w w  w.  j  av  a2  s .co  m
  * {@code (a)}
  *   One {@link StockTradingBank} is created, to serve as a {@link StockHolder}
  *   and {@link DepositHolder} for an {@link ExogenousFirm};<br>
  * {@code (b)}
  *   One {@link ExogenousFirm} is created, as well as one goods market and one
  *   labour market;<br>
  * {@code (c)}
  *   {@link UnivariateFunction}{@code s} are created for every decision on which
  *   the {@link ExogenousFirm} depends;<br>
  * {@code (d)}
  *   One {@link ExogenousGoodsBuyer} and one {@link ExogenousEmployee} are 
  *   created. Both are connected to the relevant markets;<br>
  * {@code (e)}
  *   The {@link ExogenousGoodsBuyer} is credited and debited several times, 
  *   and made subject to cash injections. It is asserted that the financial
  *   state of the {@link DepositHolder} is unchanged;<br>
  * {@code (f)}
  *   Several simulation cycles elapse. In each cycle, it is asserted that the
  *   balance sheet of the {@link ExogenousFirm} is as expected and that the
  *   {@link ExogenousFirm} has interacted with the markets as expected.
  */
@Test
public void testExogenousFirmBehaviour() {
    final StockTradingBank bank = new StockTradingBank(1.0); // 1 to pay for initial shares

    final Map<String, Pair<Double, Double>> goodsTypes = // One durable good,
            new HashMap<String, Pair<Double, Double>>(); //  one non-durable good.
    goodsTypes.put("type 1", Pair.create(1.0, 1.0)); // 100% time/use decay
    goodsTypes.put("type 2", Pair.create(0.1, 0.2)); // 10% time decay, 20% use decay.

    final SimpleGoodsMarket goodsMarket = new SimpleGoodsMarket(new ManualGoodsClassifier(goodsTypes),
            new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm()));
    goodsMarket.addInstrument("type 1");
    goodsMarket.addInstrument("type 2");

    final SimpleLabourMarket labourMarket = new SimpleLabourMarket(
            new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm()));

    final Random dice = new Random(1L);

    final class TestFunction implements UnivariateFunction {
        private final double grad;

        private TestFunction(Random dice) {
            grad = dice.nextDouble() + 1.;
        }

        @Override
        public double value(final double t) {
            return grad * (Math.floor(t) + 1.);
        }
    }

    final TimeseriesParameter<Double> deposits = createParameterFromUnivariateFunction(new TestFunction(dice)),
            commercialLoanDemand = createParameterFromUnivariateFunction(new TestFunction(dice)),
            desiredLabour = createParameterFromUnivariateFunction(new TestFunction(dice)),
            wageBidPrice = createParameterFromUnivariateFunction(new TestFunction(dice)),
            productionYield = createParameterFromUnivariateFunction(new TestFunction(dice)),
            sellingPrice = createParameterFromUnivariateFunction(new TestFunction(dice)),
            dividendPayment = createParameterFromUnivariateFunction(new TestFunction(dice)),
            maximumLendingRate = createParameterFromUnivariateFunction(new TestFunction(dice));

    final ExogenousFirm firm = new ExogenousFirm(bank, bank, 1., // 1.0 shares emitted
            1., // 1.0 per share
            "type 1", labourMarket, goodsMarket, deposits, commercialLoanDemand, desiredLabour, wageBidPrice,
            productionYield, sellingPrice, dividendPayment, maximumLendingRate,
            new CreditDemandFunction.RiskNeutralCreditDemandFunction(), new InstanceIDAgentNameFactory());

    // Check whether debits, credits and cash flow injections are exogenous:

    {
        final double startingBankCashReserve = bank.getCashReserveValue(),
                startingFirmEquity = firm.getEquity();

        firm.debit(Double.MAX_VALUE);
        firm.debit(-1.);

        try {
            firm.credit(Double.MAX_VALUE / 2.);
            firm.credit(-1.);
        } catch (InsufficientFundsException e) {
            Assert.fail();
        }

        firm.cashFlowInjection(Double.MAX_VALUE / 4.);
        firm.cashFlowInjection(-1.);

        Assert.assertEquals(bank.getCashReserveValue(), startingBankCashReserve, 1.e-12);
        Assert.assertEquals(firm.getEquity(), startingFirmEquity, 1.e-12);
    }

    // Check whether cash allocation has memory:

    firm.allocateCash(100.);
    Assert.assertEquals(firm.getAllocatedCash(), 100., 1.e-12);
    firm.allocateCash(50.);
    Assert.assertEquals(firm.getAllocatedCash(), 150., 1.e-12);
    firm.disallocateCash(151.);
    Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12);

    final ExogenousEmployee employee = new ExogenousEmployee(labourMarket);
    final ExogenousGoodsBuyer goodsBuyer = new ExogenousGoodsBuyer(goodsMarket);

    advanceTimeByOneCycle();

    double productionYieldLastValue = 0.;

    for (int i = 0; i < 10; ++i) {
        employee.setLabourSupply(100., 1.);
        goodsBuyer.setGoodsDemand("type 1", 100.);

        advanceUntilJustAfterTime(NamedEventOrderings.GOODS_INPUT_MARKET_MATCHING);

        final double depositsValueProvided = deposits.get(), desiredLabourValueProvided = desiredLabour.get(),
                wageBidPriceValueProvided = wageBidPrice.get(),
                productionYieldValueProvided = productionYield.get(),
                sellingPriceValueProvided = sellingPrice.get(),
                dividendPaymentValueProvided = dividendPayment.get();

        if (i != 0) // No trade in the first
            Assert.assertEquals( //  simulation cycle, as
                    goodsMarket.getInstrument("type 1") //  goods are yet to
                            .getWorstAskPriceAmongSellers(), //  appear in inventory.
                    sellingPriceValueProvided, 1.e-12);
        Assert.assertEquals(goodsMarket.getInstrument("type 1").getTotalSupply(), productionYieldLastValue,
                1.e-12);

        advanceUntilJustAfterTime(NamedEventOrderings.AFTER_ALL);

        Assert.assertEquals(firm.getDepositValue(), depositsValueProvided, 1.e-12);
        Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12);

        Assert.assertEquals(labourMarket.getLastLabourTotalDemand(), desiredLabourValueProvided, 1.e-12);
        Assert.assertEquals(firm.getCurrentDividend(), dividendPaymentValueProvided, 1.e-12);
        Assert.assertEquals(labourMarket.getInstrument(1).getDemandWeightedBidWage(), wageBidPriceValueProvided,
                1.e-12);

        productionYieldLastValue = productionYieldValueProvided;
    }
}

From source file:com.alvermont.terraj.planet.project.MollweideProjection.java

/**
 * Carry out the projection//from   w  w  w  .ja  va 2s  . com
 */
public void project() {
    setcolours();

    final int width = getParameters().getProjectionParameters().getWidth();
    final int height = getParameters().getProjectionParameters().getHeight();

    final double lat = getParameters().getProjectionParameters().getLatitudeRadians();
    final double lon = getParameters().getProjectionParameters().getLongitudeRadians();

    final double scale = getParameters().getProjectionParameters().getScale();

    final double hgrid = getParameters().getProjectionParameters().getHgrid();
    final double vgrid = getParameters().getProjectionParameters().getVgrid();

    final boolean doShade = getParameters().getProjectionParameters().isDoShade();

    cacheParameters();

    colours = new short[width][height];
    shades = new short[width][height];

    depth = (3 * ((int) (log2(scale * height)))) + 6;

    log.debug("MollweideProjection starting with depth set to " + depth);

    progress.progressStart(height, "Generating Terrain");

    double x;
    double y;
    double y1;
    double zz;
    double scale1;
    double cos2;
    double theta1;
    double theta2;
    int i;
    int j;
    int i1 = 1;
    int k;

    for (j = 0; j < height; ++j) {
        progress.progressStep(j);

        y1 = (2 * ((2.0 * j) - height)) / width / scale;

        if (Math.abs(y1) >= 1.0) {
            for (i = 0; i < width; ++i) {
                colours[i][j] = backgroundColour;

                if (doShade) {
                    shades[i][j] = 255;
                }
            }
        } else {
            zz = Math.sqrt(1.0 - (y1 * y1));
            y = 2.0 / Math.PI * ((y1 * zz) + Math.asin(y1));
            cos2 = Math.sqrt(1.0 - (y * y));

            if (cos2 > 0.0) {
                scale1 = (scale * width) / height / cos2 / Math.PI;
                depth = (3 * ((int) (log2(scale1 * height)))) + 3;

                for (i = 0; i < width; ++i) {
                    theta1 = (Math.PI / zz * ((2.0 * i) - width)) / width / scale;

                    if (Math.abs(theta1) > Math.PI) {
                        colours[i][j] = backgroundColour;

                        if (doShade) {
                            shades[i][j] = 255;
                        }
                    } else {
                        theta1 += (lon - (0.5 * Math.PI));

                        colours[i][j] = (short) planet0(Math.cos(theta1) * cos2, y, -Math.sin(theta1) * cos2);

                        if (doShade) {
                            shades[i][j] = shade;
                        }
                    }
                }
            }
        }
    }

    progress.progressComplete("Terrain Generated");

    log.debug("MollweideProjection complete");

    if (hgrid != 0.0) {
        /* draw horizontal gridlines */
        for (theta1 = 0.0; theta1 > -ProjectionConstants.RIGHT_ANGLE_DEGREES; theta1 -= hgrid)
            ;

        for (theta1 = theta1; theta1 < ProjectionConstants.RIGHT_ANGLE_DEGREES; theta1 += hgrid) {
            theta2 = Math.abs(theta1);
            x = Math.floor(theta2 / 5.0);
            y = (theta2 / 5.0) - x;
            y = ((1.0 - y) * mollTable[(int) x]) + (y * mollTable[(int) x + 1]);

            if (theta1 < 0.0) {
                y = -y;
            }

            j = (height / 2) + (int) (0.25 * y * width * scale);

            if ((j >= 0) && (j < height)) {
                for (i = Math.max(0,
                        (width / 2) - (int) (0.5 * width * scale * Math.sqrt(1.0 - (y * y)))); i < Math.min(
                                width,
                                (width / 2) + (int) (0.5 * width * scale * Math.sqrt(1.0 - (y * y)))); ++i)
                    colours[i][j] = BLACK;
            }
        }
    }

    if (vgrid != 0.0) {
        /* draw vertical gridlines */
        for (theta1 = 0.0; theta1 > -ProjectionConstants.CIRCLE_DEGREES; theta1 -= vgrid)
            ;

        for (theta1 = theta1; theta1 < ProjectionConstants.CIRCLE_DEGREES; theta1 += vgrid) {
            if (((Math.toRadians(theta1) - lon + (0.5 * Math.PI)) > -Math.PI)
                    && ((Math.toRadians(theta1) - lon + (0.5 * Math.PI)) <= Math.PI)) {
                x = (0.5 * (Math.toRadians(theta1) - lon + (0.5 * Math.PI)) * width * scale) / Math.PI;
                j = Math.max(0, (height / 2) - (int) (0.25 * width * scale));

                y = (2 * ((2.0 * j) - height)) / width / scale;
                i = (int) ((width / 2) + (x * Math.sqrt(1.0 - (y * y))));

                for (; j <= Math.min(height, (height / 2) + (int) (0.25 * width * scale)); ++j) {
                    y1 = (2 * ((2.0 * j) - height)) / width / scale;

                    if (Math.abs(y1) <= 1.0) {
                        i1 = (int) ((width / 2) + (x * Math.sqrt(1.0 - (y1 * y1))));

                        if ((i1 >= 0) && (i1 < width)) {
                            colours[i1][j] = BLACK;
                        }
                    }

                    if (Math.abs(y) <= 1.0) {
                        if (i < i1) {
                            for (k = i + 1; k < i1; ++k) {
                                if ((k > 00) && (k < width)) {
                                    colours[k][j] = BLACK;
                                }
                            }
                        } else if (i > i1) {
                            for (k = i - 1; k > i1; --k) {
                                if ((k >= 0) && (k < width)) {
                                    colours[k][j] = BLACK;
                                }
                            }
                        }
                    }

                    y = y1;
                    i = i1;
                }
            }
        }
    }

    if (doShade) {
        smoothshades();
    }

    doOutlining();
}

From source file:gda.device.detector.mythen.data.MythenDataFileUtils.java

public static double[][][] binMythenData(double[][][] input, double binSize) {

    // Find min/max angle
    double minAngle = Double.MAX_VALUE;
    double maxAngle = Double.MIN_VALUE;
    for (double[][] dataset : input) {
        for (double[] channel : dataset) {
            minAngle = Math.min(channel[0], minAngle);
            maxAngle = Math.max(channel[0], maxAngle);
        }// w  w  w  . ja va  2  s  . c o m
    }

    // Determine bins
    final int minBinNum = (int) Math.floor(minAngle / binSize);
    final int maxBinNum = (int) Math.ceil(maxAngle / binSize);
    final int numBins = maxBinNum - minBinNum + 1;

    final int numDatasets = input.length;

    // Create binned data array
    double[][][] binnedData = new double[numDatasets][][];

    // Create array for each dataset
    for (int dataset = 0; dataset < numDatasets; dataset++) {
        binnedData[dataset] = new double[numBins][];
    }

    // Within each dataset, create array for each bin
    // Iterate through bins first, then datasets, for efficiency (only calculate a bin's start angle once)
    for (int bin = 0; bin < numBins; bin++) {
        final double binStartAngle = (bin + minBinNum) * binSize;
        for (int dataset = 0; dataset < numDatasets; dataset++) {
            binnedData[dataset][bin] = new double[] { binStartAngle, 0 };
        }
    }

    // Bin data
    for (int dataset = 0; dataset < numDatasets; dataset++) {
        // logger.debug(String.format("Dataset %d of %d", dataset+1, numDatasets));
        final double[][] inputDataset = input[dataset];
        for (double[] channel : inputDataset) {
            final double angle = channel[0];
            final int binNumForAngle = (int) Math.floor(angle / binSize);
            final int binIndexForAngle = binNumForAngle - minBinNum;
            final double[] binForAngle = binnedData[dataset][binIndexForAngle];

            final double count = channel[1];
            // logger.debug(String.format("%.16f  %.1f = %.16f => %d/%d\tcount=%.0f", angle, binSize,
            // (angle/binSize), binNumForAngle, binIndexForAngle, count));
            binForAngle[1] = Math.max(binForAngle[1], count);
        }
    }

    return binnedData;
}

From source file:com.myGengo.alfresco.utils.MyGengoUtils.java

private static String getUniqueChildName(NodeRef parentRef, String prefix, NodeService nodeService) {
    String name = prefix + "-" + System.currentTimeMillis();

    // check that no child for the given name exists
    String finalName = name + "_" + Math.floor(Math.random() * 1000);
    int count = 0;
    while (nodeService.getChildByName(parentRef, ContentModel.ASSOC_CONTAINS, finalName) != null
            || count > 100) {/*from ww  w .j  a  v a  2s  . c o  m*/
        finalName = name + "_" + Math.floor(Math.random() * 1000);
        ++count;
    }
    return finalName;
}