List of usage examples for java.lang Math sqrt
@HotSpotIntrinsicCandidate public static double sqrt(double a)
From source file:com.opengamma.analytics.math.interpolation.TimeSquareInterpolator1D.java
@Override public Double interpolate(final Interpolator1DDataBundle data, final Double value) { Validate.notNull(value, "Value to be interpolated must not be null"); ArgumentChecker.isTrue(value > 0, "Value should be stricly positive"); Validate.notNull(data, "Data bundle must not be null"); final InterpolationBoundedValues boundedValues = data.getBoundedValues(value); final double x1 = boundedValues.getLowerBoundKey(); final double y1 = boundedValues.getLowerBoundValue(); if (data.getLowerBoundIndex(value) == data.size() - 1) { return y1; }/*from ww w. j ava 2 s . c o m*/ final double x2 = boundedValues.getHigherBoundKey(); final double y2 = boundedValues.getHigherBoundValue(); final double w = (x2 - value) / (x2 - x1); final double xy21 = x1 * y1 * y1; final double xy22 = x2 * y2 * y2; final double xy2 = w * xy21 + (1 - w) * xy22; return Math.sqrt(xy2 / value); }
From source file:bots.mctsbot.ai.bots.util.Gaussian.java
public final static double smallPhi(double x) { return 1.0 / Math.sqrt(2 * Math.PI) * Math.exp(-x * x / 2.0); }
From source file:Main.java
/** * Calculate the position of the point by using the passed points position * and strength of signal.// ww w . j av a2 s . c om * * The actual calculation is called trilateration: * https://en.wikipedia.org/wiki/Trilateration * * Also few parts from: * http://stackoverflow.com/questions/2813615/trilateration-using-3-latitude-and-longitude-points-and-3-distances * * @return the resulting point calculated. */ public static double[] triangulation(double lat0, double lon0, double r0, double lat1, double lon1, double r1, double lat2, double lon2, double r2) { // Convert to cartesian double[] p0 = latlon2cartesian(lat0, lon0); double[] p1 = latlon2cartesian(lat1, lon1); double[] p2 = latlon2cartesian(lat2, lon2); // Convert so that p0 sits at (0,0) double[] p0a = new double[] { 0, 0, 0 }; double[] p1a = new double[] { p1[X] - p0[X], p1[Y] - p0[Y], p1[Z] - p0[Z] }; double[] p2a = new double[] { p2[X] - p0[X], p2[Y] - p0[Y], p2[Z] - p0[Z] }; // All distances refers to p0, the origin Double p1distance = distance(p0a, p1a); if (p1distance == null) return null; Double p2distance = distance(p0a, p2a); if (p2distance == null) return null; // unit vector of p1a double[] p1a_ev = new double[] { p1a[X] / p1distance, p1a[Y] / p1distance, p1a[X] / p1distance }; // dot product of p1a_ev with p2a double p2b_x = p1a_ev[X] * p2a[X] + p1a_ev[Y] * p2a[Y] + p1a_ev[Z] * p2a[Z]; // finding the y of p2b (for same distance of p2a from p0a) double p2b_y = Math.sqrt(Math.abs(Math.pow(p2distance, 2) - Math.pow(p2b_x, 2))); // Convert so that p1 stays on the x line (rotates the plane) double[] p0b = new double[] { 0, 0, 0 }; double[] p1b = new double[] { p1distance, 0, 0 }; double[] p2b = new double[] { p2b_x, p2b_y, 0 }; double d = p1distance, i = p2b_x, j = p2b_y; double x = (Math.pow(r0, 2) - Math.pow(r1, 2) + Math.pow(d, 2)) / (2 * d); double y = (Math.pow(r0, 2) - Math.pow(r2, 2) + Math.pow(i, 2) + Math.pow(j, 2)) / (2 * j) - (i / j) * x; double[] pb = new double[] { x, y, 0 }; Double pbdistance = distance(p0b, pb); if (pbdistance == null) return null; // Opposite operation done for converting points from coordinate system a to b double pax = pb[X] / p1a_ev[X] + pb[Y] / p1a_ev[Y] + pb[Z] / p1a_ev[Z]; double[] pa = new double[] { pax, Math.sqrt(Math.abs(Math.pow(pbdistance, 2) - Math.pow(pax, 2))), 0 }; // Opposite operation done for converting points from coordinate system to a double p[] = new double[] { pa[X] + p0[X], pa[Y] + p0[Y], pa[Z] + p0[Z] }; // Reconvert to lat/lon return cartesian2latlon(p[X], p[Y], p[Z]); }
From source file:BezLab.java
public void mousePressed(MouseEvent e) { dragIndex = NOT_DRAGGING;// w w w . j a va2 s.c o m int minDistance = Integer.MAX_VALUE; int indexOfClosestPoint = -1; for (int i = 0; i < 4; i++) { int deltaX = xs[i] - e.getX(); int deltaY = ys[i] - e.getY(); int distance = (int) (Math.sqrt(deltaX * deltaX + deltaY * deltaY)); if (distance < minDistance) { minDistance = distance; indexOfClosestPoint = i; } } if (minDistance > NEIGHBORHOOD) return; dragIndex = indexOfClosestPoint; }
From source file:com.opengamma.analytics.financial.model.option.pricing.analytic.LogOptionModel.java
@Override public Function1D<StandardOptionDataBundle, Double> getPricingFunction(final LogOptionDefinition definition) { Validate.notNull(definition);/* w w w . j av a 2 s. c om*/ final Function1D<StandardOptionDataBundle, Double> pricingFunction = new Function1D<StandardOptionDataBundle, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(final StandardOptionDataBundle data) { Validate.notNull(data); final double s = data.getSpot(); final double k = definition.getStrike(); final double t = definition.getTimeToExpiry(data.getDate()); final double b = data.getCostOfCarry(); final double r = data.getInterestRate(t); final double sigma = data.getVolatility(t, k); final double df = Math.exp(-r * t); final double sigmaT = sigma * Math.sqrt(t); final double x = (Math.log(s / k) + t * (b - sigma * sigma * 0.5)) / sigmaT; return df * sigmaT * (_normalProbabilityDistribution.getPDF(x) + x * _normalProbabilityDistribution.getCDF(x)); } }; return pricingFunction; }
From source file:MathUtil.java
/** Arcus sin */ static public double asin(double x) { if (x < -1. || x > 1.) { return Double.NaN; }/* w w w .jav a 2s .c o m*/ if (x == -1.) { return -Math.PI / 2; } if (x == 1) { return Math.PI / 2; } return atan(x / Math.sqrt(1 - x * x)); }
From source file:com.facebook.presto.operator.aggregation.ApproximateUtils.java
/** * Computes the standard deviation for the random variable C = sum(1 / p * Bern(p)) * <br /><br />// w w w. ja v a 2 s. c o m * Derivation: * <pre> * Var(C) = Var(sum(1 / p * Bern(p))) * = sum(Var(1 / p * Bern(p))) [Bienayme formula] * = n * Var(1 / p * Bern(p)) [Bern(p) are iid] * = n * 1 / p^2 * Var(Bern(p)) [1 / p is constant] * = n * 1 / p^2 * p * (1 - p) [Variance of a Bernoulli distribution] * = n * (1 - p) / p * = samples / p * (1 - p) / p [samples = n * p, since it's only the observed rows] * </pre> * Therefore Stddev(C) = 1 / p * sqrt(samples * (1 - p)) */ public static double countError(long samples, long count) { if (count == 0) { return Double.POSITIVE_INFINITY; } double p = samples / (double) count; double error = 1 / p * Math.sqrt(samples * (1 - p)); return conservativeError(error, p, samples); }
From source file:com.clican.pluto.dataprocess.dpl.function.impl.TrackError.java
/** * @param rowSet/* w ww.jav a 2 s.c o m*/ * List * @see com.clican.pluto.dataprocess.dpl.function.MultiRowFunction#calculate(java.util.List) */ public Object calculate(List<Map<String, Object>> rowSet) throws CalculationException, PrefixAndSuffixException { if (rowSet == null || rowSet.size() == 0) { throw new CalculationException("??"); } double[] values = new double[rowSet.size()]; double sum = 0; for (int i = 0; i < rowSet.size(); i++) { Map<String, Object> row = rowSet.get(i); Double fundValue = fundNavList.getValue(row); Double indexValue = indexList.getValue(row); double value = fundValue.doubleValue() - indexValue.doubleValue(); values[i] = value; sum += value; } double avg = sum / (rowSet.size()); Variance var = new Variance(false); Double result = Math.sqrt(var.evaluate(values, avg)); return result; }
From source file:discovery.compression.kdd2011.ratio.RatioCompressionReport.java
public static void main(String[] args) throws GraphReadingException, IOException, java.text.ParseException { opts.addOption("r", true, "Goal compression ratio"); // opts.addOption( "a", // true, // "Algorithm used for compression. The default and only currently available option is \"greedy\""); //opts.addOption("cost-output",true,"Output file for costs, default is costs.txt"); //opts.addOption("cost-format",true,"Output format for "); opts.addOption("ctype", true, "Connectivity type: global or local, default is global."); opts.addOption("connectivity", false, "enables output for connectivity. Connectivity info will be written to connectivity.txt"); opts.addOption("output_bmg", true, "Write bmg file with groups to given file."); opts.addOption("algorithm", true, "Algorithm to use, one of: greedy random1 random2 bruteforce slowgreedy"); opts.addOption("hop2", false, "Only try to merge nodes that have common neighbors"); opts.addOption("kmedoids", false, "Enables output for kmedoids clustering"); opts.addOption("kmedoids_k", true, "Number of clusters to be used in kmedoids. Default is 3"); opts.addOption("kmedoids_output", true, "Output file for kmedoid clusters. Default is clusters.txt. This file will be overwritten."); opts.addOption("norefresh", false, "Use old style merging: all connectivities are not refreshed when merging"); opts.addOption("edge_attribute", true, "Attribute from bmgraph used as edge weight"); opts.addOption("only_times", false, "Only write times.txt"); //opts.addOption("no_metrics",false,"Exit after compression, don't calculate any metrics or produce output bmg for the compression."); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/* w w w . j a v a 2 s . com*/ try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } boolean connectivity = false; double ratio = 0; boolean hop2 = cmd.hasOption("hop2"); RatioCompression compression = new GreedyRatioCompression(hop2); if (cmd.hasOption("connectivity")) connectivity = true; ConnectivityType ctype = ConnectivityType.GLOBAL; CompressionMergeModel mergeModel = new PathAverageMergeModel(); if (cmd.hasOption("ctype")) { String ctypeStr = cmd.getOptionValue("ctype"); if (ctypeStr.equals("local")) { ctype = ConnectivityType.LOCAL; mergeModel = new EdgeAverageMergeModel(); } else if (ctypeStr.equals("global")) { ctype = ConnectivityType.GLOBAL; mergeModel = new PathAverageMergeModel(); } else { System.out.println(PROGRAM_NAME + ": unknown connectivity type " + ctypeStr); printHelp(); } } if (cmd.hasOption("norefresh")) mergeModel = new PathAverageMergeModelNorefresh(); if (cmd.hasOption("algorithm")) { String alg = cmd.getOptionValue("algorithm"); if (alg.equals("greedy")) { compression = new GreedyRatioCompression(hop2); } else if (alg.equals("random1")) { compression = new RandomRatioCompression(hop2); } else if (alg.equals("random2")) { compression = new SmartRandomRatioCompression(hop2); } else if (alg.equals("bruteforce")) { compression = new BruteForceCompression(hop2, ctype == ConnectivityType.LOCAL); } else if (alg.equals("slowgreedy")) { compression = new SlowGreedyRatioCompression(hop2); } else { System.out.println("algorithm must be one of: greedy random1 random2 bruteforce slowgreedy"); printHelp(); } } compression.setMergeModel(mergeModel); if (cmd.hasOption("r")) { ratio = Double.parseDouble(cmd.getOptionValue("r")); } else { System.out.println(PROGRAM_NAME + ": compression ratio not defined"); printHelp(); } if (cmd.hasOption("help")) { printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } boolean kmedoids = false; int kmedoidsK = 3; String kmedoidsOutput = "clusters.txt"; if (cmd.hasOption("kmedoids")) kmedoids = true; if (cmd.hasOption("kmedoids_k")) kmedoidsK = Integer.parseInt(cmd.getOptionValue("kmedoids_k")); if (cmd.hasOption("kmedoids_output")) kmedoidsOutput = cmd.getOptionValue("kmedoids_output"); String edgeAttrib = "goodness"; if (cmd.hasOption("edge_attribute")) edgeAttrib = cmd.getOptionValue("edge_attribute"); // This program should directly use bmgraph-java to read and // DefaultGraph should have a constructor that takes a BMGraph as an // argument. //VisualGraph vg = new VisualGraph(infile, edgeAttrib, false); //System.out.println("vg read"); //SimpleVisualGraph origSG = new SimpleVisualGraph(vg); BMGraph bmg = BMGraphUtils.readBMGraph(infile); int origN = bmg.getNodes().size(); //for(int i=0;i<origN;i++) //System.out.println(i+"="+origSG.getVisualNode(i)); System.out.println("bmgraph read"); BMNode[] i2n = new BMNode[origN]; HashMap<BMNode, Integer> n2i = new HashMap<BMNode, Integer>(); { int pi = 0; for (BMNode nod : bmg.getNodes()) { n2i.put(nod, pi); i2n[pi++] = nod; } } DefaultGraph dg = new DefaultGraph(); for (BMEdge e : bmg.getEdges()) { dg.addEdge(n2i.get(e.getSource()), n2i.get(e.getTarget()), Double.parseDouble(e.get(edgeAttrib))); } DefaultGraph origDG = dg.copy(); System.out.println("inputs read"); RatioCompression nopCompressor = new RatioCompression.DefaultRatioCompression(); ResultGraph nopResult = nopCompressor.compressGraph(dg, 1); long start = System.currentTimeMillis(); ResultGraph result = compression.compressGraph(dg, ratio); long timeSpent = System.currentTimeMillis() - start; double seconds = timeSpent * 0.001; BufferedWriter timesWriter = new BufferedWriter(new FileWriter("times.txt", true)); timesWriter.append("" + seconds + "\n"); timesWriter.close(); if (cmd.hasOption("only_times")) { System.out.println("Compression done, exiting."); System.exit(0); } BufferedWriter costsWriter = new BufferedWriter(new FileWriter("costs.txt", true)); costsWriter.append("" + nopResult.getCompressorCosts() + " " + result.getCompressorCosts() + "\n"); costsWriter.close(); double[][] origProb; double[][] compProb; int[] group = new int[origN]; for (int i = 0; i < result.partition.size(); i++) for (int x : result.partition.get(i)) group[x] = i; if (ctype == ConnectivityType.LOCAL) { origProb = new double[origN][origN]; compProb = new double[origN][origN]; DefaultGraph g = result.uncompressedGraph(); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { origProb[i][j] = dg.getEdgeWeight(i, j); compProb[i][j] = g.getEdgeWeight(i, j); } } System.out.println("Writing edge-dissimilarity"); } else { origProb = ProbDijkstra.getProbMatrix(origDG); compProb = new double[origN][origN]; System.out.println("nodeCount = " + result.graph.getNodeCount()); double[][] ccProb = ProbDijkstra.getProbMatrix(result.graph); System.out.println("ccProb.length = " + ccProb.length); System.out.println("ccProb[0].length = " + ccProb[0].length); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { if (group[i] == group[j]) compProb[i][j] = result.graph.getEdgeWeight(group[i], group[j]); else { int gj = group[j]; int gi = group[i]; compProb[i][j] = ccProb[group[i]][group[j]]; } } } System.out.println("Writing best-path-dissimilarity"); //compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } { BufferedWriter connWr = null;// if (connectivity) { connWr = new BufferedWriter(new FileWriter("connectivity.txt", true)); } double totalDiff = 0; for (int i = 0; i < origN; i++) { for (int j = i + 1; j < origN; j++) { double diff = Math.abs(origProb[i][j] - compProb[i][j]); //VisualNode ni = origSG.getVisualNode(i); //VisualNode nj = origSG.getVisualNode(j); BMNode ni = i2n[i]; BMNode nj = i2n[j]; if (connectivity) connWr.append(ni + "\t" + nj + "\t" + origProb[i][j] + "\t" + compProb[i][j] + "\t" + diff + "\n"); totalDiff += diff * diff; } } if (connectivity) { connWr.append("\n"); connWr.close(); } totalDiff = Math.sqrt(totalDiff); BufferedWriter dissWr = new BufferedWriter(new FileWriter("dissimilarity.txt", true)); dissWr.append("" + totalDiff + "\n"); dissWr.close(); } if (cmd.hasOption("output_bmg")) { BMGraph outgraph = new BMGraph(); String outputfile = cmd.getOptionValue("output_bmg"); HashMap<Integer, BMNode> nodes = new HashMap<Integer, BMNode>(); for (int i = 0; i < result.partition.size(); i++) { ArrayList<Integer> g = result.partition.get(i); if (g.size() == 0) continue; BMNode node = new BMNode("Supernode_" + i); HashMap<String, String> attributes = new HashMap<String, String>(); StringBuffer contents = new StringBuffer(); for (int x : g) contents.append(i2n[x] + ","); contents.delete(contents.length() - 1, contents.length()); attributes.put("nodes", contents.toString()); attributes.put("self-edge", "" + result.graph.getEdgeWeight(i, i)); node.setAttributes(attributes); nodes.put(i, node); outgraph.ensureHasNode(node); } for (int i = 0; i < result.partition.size(); i++) { if (result.partition.get(i).size() == 0) continue; for (int x : result.graph.getNeighbors(i)) { if (x < i) continue; BMNode from = nodes.get(i); BMNode to = nodes.get(x); if (from == null || to == null) { System.out.println(from + "->" + to); System.out.println(i + "->" + x); System.out.println(""); } BMEdge e = new BMEdge(nodes.get(i), nodes.get(x), "notype"); e.setAttributes(new HashMap<String, String>()); e.put("goodness", "" + result.graph.getEdgeWeight(i, x)); outgraph.ensureHasEdge(e); } } BMGraphUtils.writeBMGraph(outgraph, outputfile); } // k medoids! if (kmedoids) { //KMedoidsResult clustersOrig=KMedoids.runKMedoids(origProb,kmedoidsK); if (ctype == ConnectivityType.LOCAL) { compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } //KMedoidsResult compClusters = KMedoids.runKMedoids(ProbDijkstra.getProbMatrix(result.graph),kmedoidsK); KMedoidsResult clustersComp = KMedoids.runKMedoids(compProb, kmedoidsK); BufferedWriter bw = new BufferedWriter(new FileWriter(kmedoidsOutput)); for (int i = 0; i < origN; i++) { int g = group[i]; //bw.append(origSG.getVisualNode(i).getBMNode()+" "+compClusters.clusters[g]+"\n"); bw.append(i2n[i] + " " + clustersComp.clusters[i] + "\n"); } bw.close(); } System.exit(0); }
From source file:dbseer.gui.frame.DBSeerPlotPresetFrame.java
public DBSeerPlotPresetFrame(String[] chartNames, DBSeerDataSet dataset) { this.setTitle("DBSeer Visualization"); this.chartNames = chartNames; this.dataset = dataset; this.isInitSuccess = true; numCharts = chartNames.length;/*from www . j av a 2s .c o m*/ numChartInRow = (int) Math.ceil(Math.sqrt(numCharts)); try { initializeGUI(); } catch (Exception e) { e.printStackTrace(); this.isInitSuccess = false; } }