List of usage examples for java.lang Math abs
@HotSpotIntrinsicCandidate public static double abs(double a)
From source file:eu.crisis_economics.abm.model.configuration.LogNormalDistributionModelParameterConfiguration.java
/** * A lightweight test for this {@link ConfigurationComponent}. This snippet * creates a {@link Parameter}{@code <Double>} using an instance of * {@link LogNormalDistributionModelParameterConfiguration} and then tests * whether the logarithm of {@link Double} values drawn from this {@link Parameter} * have the expected mean.// ww w . j av a 2 s . co m */ public static void main(String[] args) { { final LogNormalDistributionModelParameterConfiguration configuration = new LogNormalDistributionModelParameterConfiguration(); configuration.setMu(5.0); configuration.setSigma(0.1); final ModelParameter<Double> distribution = configuration.createInjector() .getInstance(Key.get(new TypeLiteral<ModelParameter<Double>>() { })); double mean = 0.; final int numSamples = 10000000; for (int i = 0; i < numSamples; ++i) { final double value = Math.log(distribution.get()); mean += value; } mean /= numSamples; Assert.assertTrue(Math.abs(mean - 5.) < 1.e-3); } { final LogNormalDistributionModelParameterConfiguration configuration = LogNormalDistributionModelParameterConfiguration .create(5., .1); final ModelParameter<Double> distribution = configuration.createInjector() .getInstance(Key.get(new TypeLiteral<ModelParameter<Double>>() { })); final Variance variance = new Variance(); double mean = 0.; final int numSamples = 10000000; for (int i = 0; i < numSamples; ++i) { final double value = distribution.get(); mean += value; variance.increment(value); } mean /= numSamples; final double observedSigma = Math.sqrt(variance.getResult()); Assert.assertTrue(Math.abs(mean - 5.) < 1.e-3); Assert.assertTrue(Math.abs(observedSigma - .1) < 1.e-3); } }
From source file:ch.epfl.lsir.xin.test.SocialRegTest.java
/** * @param args/* ww w. j a v a 2 s . c o m*/ */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//SocialReg"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//SocialReg.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); logger.flush(); DataLoaderFile loader = new DataLoaderFile(".//data//Epinions-ratings.txt"); loader.readSimple(); //read social information loader.readRelation(".//data//Epinions-trust.txt"); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); logger.flush(); double totalMAE = 0; double totalRMSE = 0; double totalPrecision = 0; double totalRecall = 0; double totalMAP = 0; double totalNDCG = 0; double totalMRR = 0; double totalAUC = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); logger.flush(); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = dataset.getUserIDMapping(); HashMap<String, Integer> itemIDIndexMapping = dataset.getItemIDMapping(); // for( int i = 0 ; i < dataset.getUserIDs().size() ; i++ ) // { // userIDIndexMapping.put(dataset.getUserIDs().get(i), i); // } // for( int i = 0 ; i < dataset.getItemIDs().size() ; i++ ) // { // itemIDIndexMapping.put(dataset.getItemIDs().get(i) , i); // } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a social regularization recommendation model."); logger.flush(); SocialReg algo = new SocialReg(trainRatingMatrix, dataset.getRelationships(), false, ".//localModels//" + config.getString("NAME")); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); //rating prediction accuracy double RMSE = 0; double MAE = 0; double precision = 0; double recall = 0; double map = 0; double ndcg = 0; double mrr = 0; double auc = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()), itemIDIndexMapping.get(rating.getItemID())); if (prediction > algo.getMaxRating()) prediction = algo.getMaxRating(); if (prediction < algo.getMinRating()) prediction = algo.getMinRating(); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: " + MAE + " RMSE: " + RMSE); //ranking accuracy // if( algo.getTopN() > 0 ) // { // HashMap<Integer , ArrayList<ResultUnit>> results = new HashMap<Integer , ArrayList<ResultUnit>>(); // for( int i = 0 ; i < trainRatingMatrix.getRow() ; i++ ) // { // ArrayList<ResultUnit> rec = algo.getRecommendationList(i); // results.put(i, rec); // } // RankResultGenerator generator = new RankResultGenerator(results , algo.getTopN() , testRatingMatrix); // precision = generator.getPrecisionN(); // totalPrecision = totalPrecision + precision; // recall = generator.getRecallN(); // totalRecall = totalRecall + recall; // map = generator.getMAPN(); // totalMAP = totalMAP + map; // ndcg = generator.getNDCGN(); // totalNDCG = totalNDCG + ndcg; // mrr = generator.getMRRN(); // totalMRR = totalMRR + mrr; // auc = generator.getAUC(); // totalAUC = totalAUC + auc; // System.out.println("Folder --- precision: " + precision + " recall: " + // recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc); // logger.println("Folder --- precision: " + precision + " recall: " + // recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + // mrr + " auc: " + auc); // } logger.flush(); } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); System.out.println("Precision@N: " + totalPrecision / F); System.out.println("Recall@N: " + totalRecall / F); System.out.println("MAP@N: " + totalMAP / F); System.out.println("MRR@N: " + totalMRR / F); System.out.println("NDCG@N: " + totalNDCG / F); System.out.println("AUC@N: " + totalAUC / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n" + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F); logger.flush(); logger.close(); }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8092"; String devPort = "8080"; String apiUrl = "/client/api"; try {//from w w w. j a va 2 s . c om // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-dp")) { devPort = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-a")) { accountName = iter.next(); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever // cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } if (arg.equals("-w")) { wait = Integer.parseInt(iter.next()); } if (arg.equals("-z")) { zoneId = iter.next(); } if (arg.equals("-so")) { serviceOfferingId = iter.next(); } } final String server = host + ":" + port + "/"; final String developerServer = host + ":" + devPort + apiUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { @Override public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); username = Math.abs(ran.nextInt()) + "-user"; NDC.push(username); s_logger.info("Starting test for the user " + username); int response = executeDeployment(server, developerServer, username); boolean success = false; String reason = null; if (response == 200) { success = true; if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 // seconds so // the windows VM // can boot up and do a sys prep. s_logger.info("Begin Linux SSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get()); if (reason == null) { s_logger.info( "Linux SSH test successful for account " + _account.get()); } } if (reason == null) { if (internet) { s_logger.info( "Windows SSH test successful for account " + _account.get()); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (usageIterator >= numThreads) { int eventsAndBillingResponseCode = executeEventsAndBilling(server, developerServer); s_logger.info( "events and usage records command finished with response code: " + eventsAndBillingResponseCode); usageIterator = 1; } else { s_logger.info( "Skipping events and usage records for this user: usageIterator " + usageIterator + " and number of Threads " + numThreads); usageIterator++; } if ((users == null) && (accountName == null)) { s_logger.info("Sending cleanup command"); int cleanupResponseCode = executeCleanup(server, developerServer, username); s_logger.info("cleanup command finished with response code: " + cleanupResponseCode); success = (cleanupResponseCode == 200); } else { s_logger.info("Sending stop DomR / destroy VM command"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop(destroy) command finished with response code: " + stopResponseCode); success = (stopResponseCode == 200); } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("SSH test failed for account " + _account.get() + "with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info( "stop command finished with response code: " + stopResponseCode); success = false; // since the SSH test // failed, mark the // whole test as // failure } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop command finished with response code: " + stopResponseCode); success = false; // since the deploy test // failed, mark the // whole test as failure } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); Thread.sleep(wait); } catch (Exception e) { s_logger.warn("Error in thread", e); try { int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop response code: " + stopResponseCode); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:edu.usc.leqa.Main.java
/** * The main method for LEQA./*from w w w . j a va2s . c o m*/ * * @param args the command line arguments * @throws IOException */ public static void main(String[] args) throws IOException { long start, actual = 0, estimated = 0; // args = "-f ../sample_inputs/fabric.xml-t ../sample_inputs/tech.xml -i ../sample_inputs/tfc/8bitadder.tfc".split("\\s"); parseInputs(args); // -s 0.001 /* * Parsing inputs: fabric, tech & qasm files * LEQA uses parsers of QSPR */ System.out.println("Parsing technology and fabric files..."); start = System.currentTimeMillis(); layout = LayoutParser.parse(techFileAddr, fabricFileAddr); /* Converting TFC to QASM if TFC is provided. */ String inputExtension = inputFileAddr.substring(inputFileAddr.lastIndexOf('.') + 1); if (inputExtension.compareToIgnoreCase("TFC") == 0) { System.out.println("TFC file is provided. Converting to QASM..."); String qasmFileAddr = inputFileAddr.substring(0, inputFileAddr.lastIndexOf('.')) + ".qasm"; if (TFCParser.parse(inputFileAddr, qasmFileAddr) == false) { System.err.println("Failed to convert " + inputFileAddr + " to QASM format."); System.exit(-1); } inputFileAddr = qasmFileAddr; } else if (inputExtension.compareToIgnoreCase("QASM") != 0) { System.err .println("Extension " + inputExtension + " is not supported! Only qasm and tfc are supported."); System.exit(-1); } /* Parsing the QASM file */ System.out.println("Parsing QASM file..."); qasm = QASMParser.QASMParser(inputFileAddr, layout); if (qasm == null || layout == null) System.exit(-1); parseRuntime = (System.currentTimeMillis() - start) / 1000.0; /* * Invoking LEQA for estimating the latency */ System.out.println("Invoking LEQA..."); start = System.currentTimeMillis(); estimated = LEQA.leqa(qasm, layout, speed); leqaRuntime = (System.currentTimeMillis() - start) / 1000.0; /* * Invoking HL-QSPR for calculating the actual latency * This is for comparison only. It can be commented out */ if (!RuntimeConfig.SKIP) { System.out.println("Invoking QSPR..."); start = System.currentTimeMillis(); actual = QSPR.center(eds, layout, qasm); QSPRRuntime = (System.currentTimeMillis() - start) / 1000.0; } /* * Printing the results */ int separatorLength = 30; System.out.println(); System.out.println(StringUtils.center("Results", separatorLength)); System.out.println(StringUtils.repeat('-', separatorLength)); System.out.println("Estimated value:\t" + estimated); if (!RuntimeConfig.SKIP) { System.out.println("Actual value:\t\t" + actual); System.out.printf("Error:\t\t\t%.2f%%" + lineSeparator, (Math.abs(estimated - actual) * 100.0 / actual)); } System.out.println(StringUtils.repeat('-', separatorLength)); System.out.println("Parsing overhead:\t" + parseRuntime + "s"); System.out.println("LEQA runtime:\t\t" + leqaRuntime + "s"); if (!RuntimeConfig.SKIP) { System.out.println("QSPR time:\t\t" + QSPRRuntime + "s"); System.out.printf("Speed up:\t\t%.2f" + lineSeparator, QSPRRuntime / leqaRuntime); } }
From source file:io.anserini.index.UserPostFrequencyDistribution.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("collection").hasArg() .withDescription("source collection directory").create(COLLECTION_OPTION)); options.addOption(OptionBuilder.withArgName("property").hasArg() .withDescription("source collection directory").create("property")); options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg() .withDescription("source collection directory").create("collection_pattern")); CommandLine cmdline = null;/*from www. j a va2 s. c om*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); textOptions.setStoreTermVectors(true); LOG.info("collection: " + collectionPath); LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern")); LOG.info("property " + cmdline.getOptionValue("property")); LongOpenHashSet deletes = null; long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file, cmdline.getOptionValue("collection_pattern")); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { stream.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ; System.out.println("# of users indexed this round: " + userIndexedCount); System.out.println("Shutting down"); } }); Status status; boolean readerNotInitialized = true; try { Properties prop = new Properties(); while ((status = stream.next()) != null) { // try{ // status = DataObjectFactory.createStatus(s); // if (status==null||status.getText() == null) { // continue; // }}catch(Exception e){ // // } // boolean pittsburghRelated = false; try { if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getPlace().contains("Pittsburgh, PA")) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getUserLocation().contains("Pittsburgh, PA")) pittsburghRelated = true; } catch (Exception e) { } try { if (status.getText().contains("Pittsburgh")) pittsburghRelated = true; } catch (Exception e) { } if (pittsburghRelated) { int previousPostCount = 0; if (prop.containsKey(String.valueOf(status.getUserid()))) { previousPostCount = Integer .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]); } prop.setProperty(String.valueOf(status.getUserid()), String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount)); if (prop.size() > 0 && prop.size() % 1000 == 0) { Runtime runtime = Runtime.getRuntime(); runtime.gc(); System.out.println("Property size " + prop.size() + "Memory used: " + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n"); } OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false); prop.store(output, null); output.close(); } } // prop.store(output, null); LOG.info(String.format("Total of %s statuses added", userIndexedCount)); LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { stream.close(); } }
From source file:msi.gaml.operators.Maths.java
public static void main(final String[] args) throws ParseException { java.lang.System.out.println("Various format tests"); java.lang.System.out.println("NumberFormat.parse1e1 = " + NumberFormat.getInstance(Locale.US).parse("1e1")); java.lang.System.out.println("Double.parse 1e1 = " + Double.parseDouble("1e1")); java.lang.System.out/*from w w w. jav a 2s. c o m*/ .println("NumberFormat.parse 1E1 = " + NumberFormat.getInstance(Locale.US).parse("1E1")); java.lang.System.out.println("Double.parse 1E1 = " + Double.parseDouble("1E1")); java.lang.System.out .println("NumberFormat.parse 1.0e1 = " + NumberFormat.getInstance(Locale.US).parse("1.0e1")); java.lang.System.out.println("Double.parse 1.0e1 = " + Double.parseDouble("1.0e1")); java.lang.System.out.println( "NumberFormat.parse 0.001E+10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E+10")); java.lang.System.out.println("Double.parse 0.001E+10 = " + Double.parseDouble("0.001E+10")); java.lang.System.out.println( "NumberFormat.parse 0.001E-10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E-10")); java.lang.System.out.println("Double.parse 0.001E-10 = " + Double.parseDouble("0.001E-10")); java.lang.System.out .println("NumberFormat.parse 0.001e-10 =" + NumberFormat.getInstance(Locale.US).parse("0.001e-10")); java.lang.System.out.println("Double.parse 0.001e-10 = " + Double.parseDouble("0.001e-10")); java.lang.System.out.println("Various arithmetic tests"); java.lang.System.out.println("cos(PI) = " + Maths.cos_rad(PI)); java.lang.System.out.println("sin_rad(0.0) = " + sin_rad(0.0)); java.lang.System.out.println("tan_rad(0.0) = " + tan_rad(0.0)); java.lang.System.out.println("sin(360) = " + sin(360)); java.lang.System.out.println("sin(-720) = " + sin(-720)); java.lang.System.out.println("sin(360.0) = " + sin(360.0)); java.lang.System.out.println("sin(-720.0) = " + sin(-720.0)); java.lang.System.out.println("sin(90) = " + sin(90)); java.lang.System.out.println("sin(45) = " + sin(45)); java.lang.System.out.println("sin(0) = " + sin(0)); java.lang.System.out.println("sin(135) = " + sin(135)); java.lang.System.out.println("Math.sin(360.0) = " + Math.sin(2 * Math.PI)); // java.lang.System.out.println("3.0 = 3" + (3d == 3)); // java.lang.System.out.println("3.0 != 3" + (3d != 3)); java.lang.System.out.println("floor and ceil 2.7 " + floor(2.7) + " and " + ceil(2.7)); java.lang.System.out.println("floor and ceil -2.7 " + floor(-2.7) + " and " + ceil(-2.7)); java.lang.System.out.println("floor and ceil -2 " + floor(-2) + " and " + ceil(-2)); java.lang.System.out.println("floor and ceil 3 " + floor(3) + " and " + ceil(3)); double atan2diff = 0; double atan2diff2 = 0; Random rand = new Random(); long s1 = 0; long t1 = 0; long t2 = 0; long t3 = 0; // for ( int i = 0; i < 10000000; i++ ) { // double x = rand.nextDouble(); // double y = rand.nextDouble(); // s1 = java.lang.System.currentTimeMillis(); // double a1 = Math.atan2(x, y); // t1 += java.lang.System.currentTimeMillis() - s1; // s1 = java.lang.System.currentTimeMillis(); // double a2 = FastMath.atan2(x, y); // t2 += java.lang.System.currentTimeMillis() - s1; // s1 = java.lang.System.currentTimeMillis(); // double a3 = Maths.atan2Opt2(x, y); // t3 += java.lang.System.currentTimeMillis() - s1; // // atan2diff += Math.abs(a1 - a2); // atan2diff2 += Math.abs(a1 - a3); // } // java.lang.System.out.println("atan2diff : " + atan2diff + " atan2diff2 : " + atan2diff2 + " t1 : " + t1 + // " t2 : " + t2 + " t3 : " + t3); long t4 = 0; long t5 = 0; long t6 = 0; double distDiff1 = 0; double distDiff2 = 0; for (int i = 0; i < 1000000; i++) { double x1 = rand.nextDouble(); double y1 = rand.nextDouble(); double x2 = rand.nextDouble(); double y2 = rand.nextDouble(); Coordinate c1 = new Coordinate(x1, y1); Coordinate c2 = new Coordinate(x2, y2); s1 = java.lang.System.currentTimeMillis(); double a1 = Math.hypot(x2 - x1, y2 - y1); t4 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); double a2 = FastMath.hypot(x2 - x1, y2 - y1); t5 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); double a3 = c1.distance(c2); t6 += java.lang.System.currentTimeMillis() - s1; distDiff1 += Math.abs(a1 - a2); distDiff2 += Math.abs(a1 - a3); } java.lang.System.out.println("distDiff1 : " + distDiff1 + " distDiff2 : " + distDiff2 + " t4 : " + t4 + " t5 : " + t5 + " t6 : " + t6); long t7 = 0; long t8 = 0; distDiff1 = 0; for (int i = 0; i < 1000000; i++) { double a1, a2; double x1 = rand.nextDouble(); double x2 = rand.nextDouble(); double y1 = rand.nextDouble(); double y2 = rand.nextDouble(); double z1 = 0.0; double z2 = 0.0; GamaPoint c2 = new GamaPoint(x2, y2, z2); s1 = java.lang.System.currentTimeMillis(); if (z1 == 0d && c2.getZ() == 0d) { a1 = hypot(x1, x2, y1, y2); } else { a1 = hypot(x1, x2, y1, y2, z1, z2); } t7 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); a2 = hypot(x1, x2, y1, y2, z1, c2.getZ()); t8 += java.lang.System.currentTimeMillis() - s1; distDiff1 += Math.abs(a1 - a2); } java.lang.System.out.println( "with 0.0 check : " + t7 + " with direct 3 parameters call : " + t8 + " distance : " + distDiff1); // java.lang.System.out.println("Infinity to int:" + (int) Double.POSITIVE_INFINITY); // java.lang.System.out.println("NaN to int:" + (int) Double.NaN); // GuiUtils.debug("(int) (1.0/0.0):" + (int) (1.0 / 0.0)); // GuiUtils.debug("(int) (1.0/0):" + (int) (1.0 / 0)); // GuiUtils.debug("(int) (1.0/0d):" + (int) (1 / 0d)); // GuiUtils.debug("(int) (1/0):" + 1 / 0); }
From source file:Main.java
private static double UFa(double paramDouble) { return Math.abs(paramDouble); }
From source file:Main.java
static int getDistance(int rssi) { int irssi = Math.abs(rssi); double power = (irssi - 70.0) / (10 * 2.0); power = Math.pow(10d, power); power = power * 100;/* w ww .ja v a2 s. c o m*/ return (int) power; }
From source file:Main.java
public final static int absInt(double d) { return (int) Math.abs(d); }
From source file:Main.java
private static boolean isClose(float f, float f2) { return Math.abs(f - f2) < 0.001f; }