Example usage for java.lang Math PI

List of usage examples for java.lang Math PI

Introduction

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

Prototype

double PI

To view the source code for java.lang Math PI.

Click Source Link

Document

The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

Usage

From source file:edu.indiana.d2i.datacatalog.dashboard.api.USStates.java

public static String getStates(String statesFilePath)
        throws ParserConfigurationException, IOException, SAXException {
    JSONObject statesFeatureCollection = new JSONObject();
    statesFeatureCollection.put("type", "FeatureCollection");
    JSONArray features = new JSONArray();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {/*from w ww  .j  av a 2s .co  m*/
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document dom = documentBuilder.parse(new FileInputStream(new File(statesFilePath)));
        Element docElement = dom.getDocumentElement();
        NodeList states = docElement.getElementsByTagName("state");
        for (int i = 0; i < states.getLength(); i++) {
            Node state = states.item(i);
            JSONObject stateObj = new JSONObject();
            stateObj.put("type", "Feature");
            JSONObject geometry = new JSONObject();
            geometry.put("type", "Polygon");
            JSONArray coordinates = new JSONArray();
            JSONArray coordinateSub = new JSONArray();
            NodeList points = ((Element) state).getElementsByTagName("point");
            for (int j = 0; j < points.getLength(); j++) {
                Node point = points.item(j);
                JSONArray pointObj = new JSONArray();
                float lat = Float.parseFloat(((Element) point).getAttribute("lat"));
                float lng = Float.parseFloat(((Element) point).getAttribute("lng"));
                double trLng = lng * 20037508.34 / 180;
                double trLat = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
                pointObj.add(lng);
                pointObj.add(lat);
                coordinateSub.add(pointObj);
            }
            geometry.put("coordinates", coordinates);
            coordinates.add(coordinateSub);
            stateObj.put("geometry", geometry);
            JSONObject name = new JSONObject();
            name.put("Name", ((Element) state).getAttribute("name"));
            name.put("colour", "#FFF901");
            stateObj.put("properties", name);
            features.add(stateObj);
        }
        statesFeatureCollection.put("features", features);
        return statesFeatureCollection.toJSONString();
    } catch (ParserConfigurationException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (FileNotFoundException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (SAXException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    } catch (IOException e) {
        log.error("Error while processing states.xml.", e);
        throw e;
    }
}

From source file:endrov.nucAutoJH.FitGaussian.java

private static double[] fitGaussian2D_(EvPixels p, double sigmaInit, final double midxInit,
        final double midyInit) {
    //sigma00, sigma01, sigma11, mu_x, mu_y, c 

    p = p.getReadOnly(EvPixelsType.DOUBLE);
    final double[] arrPixels = p.getArrayDouble();
    final int w = p.getWidth();
    final int h = p.getHeight();

    int extent = (int) Math.round(3 * sigmaInit);
    extent = Math.max(extent, 2);

    final int sx = Math.max(0, (int) (midxInit - extent));
    final int ex = Math.min(w, (int) (midxInit + extent + 1)); //+1 to the right?
    final int sy = Math.max(0, (int) (midyInit - extent));
    final int ey = Math.min(h, (int) (midyInit + extent + 1));

    double minIntensity = Double.MAX_VALUE;
    double maxIntensity = Double.MIN_VALUE;
    for (int y = sy; y < ey; y++) {
        int base = y * w;
        double dy2 = y - midyInit;
        dy2 = dy2 * dy2;/*w w  w  .jav a  2  s.c  o m*/
        for (int x = sx; x < ex; x++) {
            double dx2 = x - midxInit;
            dx2 = dx2 * dx2;
            double t = arrPixels[base + x];
            //if(dx2+dy2<=extent*extent)
            {
                if (t < minIntensity)
                    minIntensity = t;
                if (t > maxIntensity)
                    maxIntensity = t;
            }
        }
    }

    //double[] weights=new double[]{1};
    double[] startPoint = new double[] { sigmaInit, 0, sigmaInit, midxInit, midyInit, minIntensity,
            maxIntensity - minIntensity };
    //double[] output=new double[startPoint.length];

    try {
        MultivariateRealFunction func = new MultivariateRealFunction() {
            //      opt.optimize(

            public double value(double[] arg) throws FunctionEvaluationException, IllegalArgumentException {
                double sigma00 = arg[0];
                double sigma01 = arg[1];
                double sigma11 = arg[2];
                double mu0 = arg[3];
                double mu1 = arg[4];
                double C = arg[5];
                double D = arg[6];

                double sumError = 0;

                Matrix2d sigma = new Matrix2d(sigma00, sigma01, sigma01, sigma11);
                Matrix2d sigmaInv = new Matrix2d();
                sigma.invert(sigmaInv);
                double sigmaDet = sigma.determinant();
                double front = 1.0 / (2 * Math.PI * Math.sqrt(sigmaDet));
                //System.out.println("front: "+front);
                //System.out.println("sigma inv "+sigmaInv);

                if (mu0 < sx || mu0 > ex)
                    sumError += 1000000;
                if (mu1 < sy || mu1 > ey)
                    sumError += 1000000;
                if (sigma00 < 1)
                    sumError += 1000000;
                //if(sigma01<0)               sumError+=1000000;
                if (sigma11 < 1)
                    sumError += 1000000;
                if (D <= 0)
                    sumError += 1000000;

                for (int y = sy; y < ey; y++) {
                    int base = y * w;
                    double dy2 = y - midyInit;
                    dy2 = dy2 * dy2;
                    for (int x = sx; x < ex; x++) {
                        double dx2 = x - midxInit;
                        dx2 = dx2 * dx2;
                        double thisReal = arrPixels[base + x];
                        //                  if(dx2+dy2<=extent*extent)
                        {
                            //               DoubleMatrix2D sigma=new DenseDoubleMatrix2D(new double[][]{{sigma00,sigma01},{sigma01,sigma11}});
                            //double sigmaDet=sigma00*sigma11-sigma01*sigma01;

                            double dx0 = x - mu0;
                            double dx1 = y - mu1;

                            //http://en.wikipedia.org/wiki/Multivariate_normal_distribution

                            Vector2d vX = new Vector2d(dx0, dx1);
                            Vector2d op = new Vector2d(vX);
                            sigmaInv.transform(op);
                            double upper = -0.5 * op.dot(vX);
                            double exp = Math.exp(upper);

                            //System.out.println("front "+front+" "+exp+" C "+C+" thisreal"+thisReal+" upper "+upper);

                            if (upper > -0.4)
                                exp = 1;
                            else
                                exp = Math.max(0, 1 + upper + 0.4);

                            /*
                            if(exp<0.7)
                               exp=0;
                            else
                               exp=1;
                            */

                            double thisExpected = D * front * exp + C;
                            double diff = thisExpected - thisReal;
                            sumError += diff * diff;

                        }
                    }
                }

                //System.out.println(sigma00+"\t"+sigma01+"\t"+sigma11+"\tC"+C+"\tmu "+mu0+","+mu1+"\terr "+sumError);
                return sumError;
                //            return new double[]{sumError};
            }

        };

        NelderMead opt = new NelderMead();
        //LevenbergMarquardtOptimizer opt=new LevenbergMarquardtOptimizer();
        opt.setMaxIterations(10000);
        RealPointValuePair pair = opt.optimize(func, GoalType.MINIMIZE, startPoint);

        int numit = opt.getIterations();
        System.out.println("#it " + numit);
        System.out.println("err " + func.value(pair.getPointRef()));
        return pair.getPointRef();

        //         for(int i=0;i<startPoint.length;i++)
        //         System.out.println("i: "+i+"  "+output[i]);
        //, output, weights, startPoint);
    }
    /*
    catch (MaxIterationsExceededException e)
       {
       System.out.println("max it reached");
               
       }*/
    catch (Exception e) {
        e.printStackTrace();
    }

    //Maybe this is a bad point?
    System.out.println("max it reached");
    return startPoint;
    //      return output;
}

From source file:net.sourceforge.processdash.ui.lib.chart.DiscLegendAxis.java

/**
 * Converts a disc area to a coordinate in Java2D space on the legend axis.
 */// www  .  j  av a 2  s  .c om
@Override
public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge) {

    if (discItemDistributor == null) {
        // This should not happen since prior to using a legend axis, a DiscPlot
        //  should set a DiscItemDistributor.
        return 0.0;
    }

    double discRadius = Math.sqrt(Math.abs(value) / Math.PI);
    double discDiameter = 2 * discRadius;
    double scaledDiameter = discDiameter * discItemDistributor.getScale();
    double java2DValue = area.getMaxY() - scaledDiameter;

    return java2DValue;
}

From source file:gedi.util.math.stat.distributions.PoissonBinomial.java

private void preprocess() {
    int n = pp.length;
    m = n + 1;/*from  w  w w  .  ja  va  2  s  .co m*/
    int nextPowerOf2 = Integer.highestOneBit(m);
    if (nextPowerOf2 != m)
        nextPowerOf2 <<= 1;
    m = nextPowerOf2;
    n = m - 1;

    int ins = 0;
    int start = 0;
    for (int i = 1; i < pp.length; i++) {
        if (Math.abs(pp[i] - pp[start]) > 1E-10) {
            if (i - start > 1) {
                double p = pp[start];
                pp[ins++] = -(i - start);
                pp[ins++] = p;
            } else {
                pp[ins++] = pp[i - 1];
            }
            start = i;
        }
    }

    if (pp.length - start > 1) {
        double p = pp[start];
        pp[ins++] = -(pp.length - start);
        pp[ins++] = p;
    } else {
        pp[ins++] = pp[pp.length - 1];
    }

    double delta = 2 * Math.PI / m;
    z = new Complex[m];
    z[0] = new Complex(1, 0);

    for (int i = 1; i <= Math.ceil(n / 2.0); i++) {
        double tt = i * delta;

        //         for(int j=0;j<pp.length;j++)
        //         {
        //            double pj=j<opp.length?opp[j]:0;
        //            double ax=1-pj+pj*Math.cos(tt);
        //            double bx=pj*Math.sin(tt);
        //            double tmp1=Math.sqrt(ax*ax+bx*bx);
        //            double tmp2=Math.atan2(bx,ax); //atan2(x,y)
        //            c1o+=Math.log(tmp1);
        //            c2o+=tmp2;
        //         }

        double c1 = 0.00;
        double c2 = 0.00;
        for (int j = 0; j < ins; j++) {
            double pj = pp[j];
            double f = 1;
            if (pj < 0) {
                f = -pj;
                pj = pp[++j];
            }

            double ax = 1 - pj + pj * Math.cos(tt);
            double bx = pj * Math.sin(tt);
            double tmp1 = Math.sqrt(ax * ax + bx * bx);
            double tmp2 = Math.atan2(bx, ax); //atan2(x,y)
            c1 += Math.log(tmp1) * f;
            c2 += tmp2 * f;
        }
        z[i] = new Complex(Math.exp(c1) * Math.cos(c2), Math.exp(c1) * Math.sin(c2));
        z[z.length - i] = z[i].conjugate();
    }
    FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
    z = fft.transform(z, TransformType.FORWARD);
}

From source file:AsymptoticFreedom.GraphViewPanel.java

public JFreeChart getResultChart() {
    // XY ?//from ww w  . j ava  2  s .  c o m
    int quark_size = ViewPanel.quark_list.size();
    if (quark_size < 2)
        return new JFreeChart(new XYPlot());

    // XY Dataset  
    XYSeriesCollection data = new XYSeriesCollection();
    //System.out.println(series.get(0).getY(30));
    for (XYSeries s : series) {
        data.addSeries(s);
    }

    final JFreeChart chart = ChartFactory.createXYLineChart("Potential", "Distance", "Potential", data,
            PlotOrientation.VERTICAL, true, true, false);
    chart.setTitle("Potential of quarks"); //  ?
    XYPlot plot = (XYPlot) chart.getPlot();
    //plot.addRangeMarker(new ValueMarker(15,Color.RED,new BasicStroke(2.0f)));
    for (int i = 0; i < quark_size; i++) {
        for (int j = i + 1; j < quark_size; j++) {
            Quark quark1 = ViewPanel.quark_list.get(i);
            Quark quark2 = ViewPanel.quark_list.get(j);
            double distance = quark1.pos.distance(quark2.pos);
            double value = quark1.calculatePotential(quark2);
            String anno_title = String.format("V_ %c-%c", quark1.color.charAt(0), quark2.color.charAt(0));
            //System.out.println(anno_title);
            XYPointerAnnotation pointer = new XYPointerAnnotation(anno_title, distance, value,
                    3.0 * Math.PI / 4.0);
            plot.addAnnotation(pointer);
        }
    }
    plot.getRangeAxis().setRange(-500, 4000);
    return chart;
}

From source file:endrov.typeLineageAutoNucJH.FitGaussian.java

private static double[] fitGaussian2D_(EvPixels p, double sigmaInit, final double midxInit,
        final double midyInit) {
    //sigma00, sigma01, sigma11, mu_x, mu_y, c 

    p = p.getReadOnly(EvPixelsType.DOUBLE);
    final double[] arrPixels = p.getArrayDouble();
    final int w = p.getWidth();
    final int h = p.getHeight();

    int extent = (int) Math.round(3 * sigmaInit);
    extent = Math.max(extent, 2);

    final int sx = Math.max(0, (int) (midxInit - extent));
    final int ex = Math.min(w, (int) (midxInit + extent + 1)); //+1 to the right?
    final int sy = Math.max(0, (int) (midyInit - extent));
    final int ey = Math.min(h, (int) (midyInit + extent + 1));

    double minIntensity = Double.MAX_VALUE;
    double maxIntensity = -Double.MAX_VALUE;
    for (int y = sy; y < ey; y++) {
        int base = y * w;
        double dy2 = y - midyInit;
        dy2 = dy2 * dy2;//  ww  w .  j  av a2s  . co  m
        for (int x = sx; x < ex; x++) {
            double dx2 = x - midxInit;
            dx2 = dx2 * dx2;
            double t = arrPixels[base + x];
            //if(dx2+dy2<=extent*extent)
            {
                if (t < minIntensity)
                    minIntensity = t;
                if (t > maxIntensity)
                    maxIntensity = t;
            }
        }
    }

    //double[] weights=new double[]{1};
    double[] startPoint = new double[] { sigmaInit, 0, sigmaInit, midxInit, midyInit, minIntensity,
            maxIntensity - minIntensity };
    //double[] output=new double[startPoint.length];

    try {
        MultivariateRealFunction func = new MultivariateRealFunction() {
            //      opt.optimize(

            public double value(double[] arg) throws FunctionEvaluationException, IllegalArgumentException {
                double sigma00 = arg[0];
                double sigma01 = arg[1];
                double sigma11 = arg[2];
                double mu0 = arg[3];
                double mu1 = arg[4];
                double C = arg[5];
                double D = arg[6];

                double sumError = 0;

                Matrix2d sigma = new Matrix2d(sigma00, sigma01, sigma01, sigma11);
                Matrix2d sigmaInv = new Matrix2d();
                sigma.invert(sigmaInv);
                double sigmaDet = sigma.determinant();
                double front = 1.0 / (2 * Math.PI * Math.sqrt(sigmaDet));
                //System.out.println("front: "+front);
                //System.out.println("sigma inv "+sigmaInv);

                if (mu0 < sx || mu0 > ex)
                    sumError += 1000000;
                if (mu1 < sy || mu1 > ey)
                    sumError += 1000000;
                if (sigma00 < 1)
                    sumError += 1000000;
                //if(sigma01<0)               sumError+=1000000;
                if (sigma11 < 1)
                    sumError += 1000000;
                if (D <= 0)
                    sumError += 1000000;

                for (int y = sy; y < ey; y++) {
                    int base = y * w;
                    double dy2 = y - midyInit;
                    dy2 = dy2 * dy2;
                    for (int x = sx; x < ex; x++) {
                        double dx2 = x - midxInit;
                        dx2 = dx2 * dx2;
                        double thisReal = arrPixels[base + x];
                        //                  if(dx2+dy2<=extent*extent)
                        {
                            //               DoubleMatrix2D sigma=new DenseDoubleMatrix2D(new double[][]{{sigma00,sigma01},{sigma01,sigma11}});
                            //double sigmaDet=sigma00*sigma11-sigma01*sigma01;

                            double dx0 = x - mu0;
                            double dx1 = y - mu1;

                            //http://en.wikipedia.org/wiki/Multivariate_normal_distribution

                            Vector2d vX = new Vector2d(dx0, dx1);
                            Vector2d op = new Vector2d(vX);
                            sigmaInv.transform(op);
                            double upper = -0.5 * op.dot(vX);
                            double exp = Math.exp(upper);

                            //System.out.println("front "+front+" "+exp+" C "+C+" thisreal"+thisReal+" upper "+upper);

                            if (upper > -0.4)
                                exp = 1;
                            else
                                exp = Math.max(0, 1 + upper + 0.4);

                            /*
                            if(exp<0.7)
                               exp=0;
                            else
                               exp=1;
                            */

                            double thisExpected = D * front * exp + C;
                            double diff = thisExpected - thisReal;
                            sumError += diff * diff;

                        }
                    }
                }

                //System.out.println(sigma00+"\t"+sigma01+"\t"+sigma11+"\tC"+C+"\tmu "+mu0+","+mu1+"\terr "+sumError);
                return sumError;
                //            return new double[]{sumError};
            }

        };

        NelderMead opt = new NelderMead();
        //LevenbergMarquardtOptimizer opt=new LevenbergMarquardtOptimizer();
        opt.setMaxIterations(10000);
        RealPointValuePair pair = opt.optimize(func, GoalType.MINIMIZE, startPoint);

        int numit = opt.getIterations();
        System.out.println("#it " + numit);
        System.out.println("err " + func.value(pair.getPointRef()));
        return pair.getPointRef();

        //         for(int i=0;i<startPoint.length;i++)
        //         System.out.println("i: "+i+"  "+output[i]);
        //, output, weights, startPoint);
    }
    /*
    catch (MaxIterationsExceededException e)
       {
       System.out.println("max it reached");
               
       }*/
    catch (Exception e) {
        e.printStackTrace();
    }

    //Maybe this is a bad point?
    System.out.println("max it reached");
    return startPoint;
    //      return output;
}

From source file:Float11.java

static public double atan2(double y, double x) {
    // if x=y=0/*from  w  w  w  .j  a va  2 s .c  o  m*/
    if (y == 0. && x == 0.)
        return 0.;
    // if x>0 atan(y/x)
    if (x > 0.)
        return atan(y / x);
    // if x<0 sign(y)*(pi - atan(|y/x|))
    if (x < 0.) {
        if (y < 0.)
            return -(Math.PI - atan(y / x));
        else
            return Math.PI - atan(-y / x);
    }
    // if x=0 y!=0 sign(y)*pi/2
    if (y < 0.)
        return -Math.PI / 2.;
    else
        return Math.PI / 2.;
}

From source file:BooksDemo.java

private void rotateBook() {
    if (!isBookShowingFront()) {
        rotator1.setMinimumAngle((float) Math.PI * 1.0f);
        rotator1.setMaximumAngle(0.0f);//from ww w .  ja va2  s.co  m
    } else {
        rotator1.setMinimumAngle(0.0f);
        rotator1.setMaximumAngle((float) Math.PI * 1.0f);
    }

    front = !front;
    rotor1Alpha.setStartTime(System.currentTimeMillis());
}

From source file:com.qaant.threadModels.TWhaley.java

private void wWhaley() {

    tipoEjercicio = AMERICAN;/*from   www  . j  ava  2s .  c  om*/

    //     q=(tipoContrato==STOCK) ? dividendRate:rate; 
    //q: si es una accion q es el dividendo, si es un futuro q se toma la rate para descontar el valor futr a presente 
    //Se hace este reemplazo para poder usar la misma form en STOCK y FUTURO

    double xx;

    switch (tipoContrato) {
    case STOCK:
        q = dividendRate;
        b = rate;
        break;

    case FUTURES:
        q = rate;
        b = 0;
        break;
    }
    double vlt2 = volatModel * volatModel;
    double VltSqrDayYear = volatModel * sqrDayYear;
    double h = 1 - z; //descuento para valor presente

    double alfa = 2 * rate / vlt2;
    double beta = 2 * (b - q) / vlt2;

    double lambda = (-(beta - 1) + cpFlag * Math.sqrt((beta - 1) * (beta - 1) + 4 * alfa / h)) / 2;

    double eex = Math.exp(-q * dayYear);//descuento por dividendos

    double s1 = strike;
    double zz = 1 / Math.sqrt(2 * Math.PI);
    double zerror = 1;
    do {
        double d1 = (Math.log(s1 / strike) + ((rate - q) + vlt2 / 2) * dayYear) / VltSqrDayYear;
        xx = (1 - eex * new NormalDistribution().cumulativeProbability(cpFlag * d1));

        double corr = s1 / lambda * xx;

        QBlackScholes option = new QBlackScholes(tipoContrato, s1, volatModel, dividendRate, callPut, strike,
                daysToExpiration, rate, 0);

        double mBlackScholes = option.getPrima();
        double rhs = mBlackScholes + cpFlag * corr;

        double lhs = cpFlag * (s1 - strike);
        zerror = lhs - rhs;
        double nd1 = zz * Math.exp(-0.5 * d1 * d1); //standard normal prob?
        double slope = cpFlag * (1 - 1 / lambda) * xx + 1 / lambda * (eex * nd1) * 1 / VltSqrDayYear;
        s1 = s1 - zerror / slope;

    } while (Math.abs(zerror) > 0.000001);

    double a = cpFlag * s1 / lambda * xx;

    switch (callPut) {
    case CALL: //Call
        if (underlyingValue >= s1) {
            prima = underlyingValue - strike;
        } else {
            prima += a * Math.pow((underlyingValue / s1), lambda);
        }
        break;

    case PUT: //Put
        if (underlyingValue <= s1) {
            prima = strike - underlyingValue;
        } else {
            prima += a * Math.pow((underlyingValue / s1), lambda);
        }
        //prima=10.1;
        break;
    }
}

From source file:Main.java

public void paint(Graphics g, JComponent c) {

    JLabel label = (JLabel) c;
    String text = label.getText();
    Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();

    if ((icon == null) && (text == null)) {
        return;/* w w  w.  j  av a2  s. com*/
    }

    FontMetrics fm = g.getFontMetrics();
    paintViewInsets = c.getInsets(paintViewInsets);

    paintViewR.x = paintViewInsets.left;
    paintViewR.y = paintViewInsets.top;

    // Use inverted height & width
    paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
    paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);

    paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
    paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;

    String clippedText = layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);

    Graphics2D g2 = (Graphics2D) g;
    AffineTransform tr = g2.getTransform();
    if (clockwise) {
        g2.rotate(Math.PI / 2);
        g2.translate(0, -c.getWidth());
    } else {
        g2.rotate(-Math.PI / 2);
        g2.translate(-c.getHeight(), 0);
    }

    if (icon != null) {
        icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
    }

    if (text != null) {
        int textX = paintTextR.x;
        int textY = paintTextR.y + fm.getAscent();

        if (label.isEnabled()) {
            paintEnabledText(label, g, clippedText, textX, textY);
        } else {
            paintDisabledText(label, g, clippedText, textX, textY);
        }
    }

    g2.setTransform(tr);
}