List of usage examples for java.util Random nextFloat
public float nextFloat()
From source file:uk.ac.soton.itinnovation.ecc.service.utils.ExplorerDemoData.java
private EccINTRATSeries createQoSDataSeries(String seriesKey, float minValue, float maxValue, float changeRange, float influence, int influenceCount, int count) { ArrayList<EccMeasurement> dataSeries = new ArrayList<>(); Date ts = new Date(expStartDate.getTime()); float value = 0.0f; Random rand = new Random(); for (int i = 0; i < count; i++) { // Create measurement and add to data set EccMeasurement m = new EccMeasurement(); m.setTimestamp(ts);/*ww w .ja v a2 s . c o m*/ dataSeries.add(m); // Update next value value += (rand.nextFloat() * changeRange) - (rand.nextFloat() * changeRange); // Boundary if (value < minValue) value = minValue; else if (value > maxValue) value = maxValue; // Set measurement value with influence (or not) if (influenceCount > 0) { float infValue = influence + value; // Check just floor boundary with influence if (infValue < minValue) infValue = minValue; m.setValue(Float.toString(infValue)); --influenceCount; } else m.setValue(Float.toString(value)); // Update next time stamp ts = new Date(ts.getTime() + 60000); } return new EccINTRATSeries(seriesKey, false, dataSeries); }
From source file:lob.VisualisationGUI.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: boolean validEntry = true; //Convert all entries into acceptable format for broker. Alert user if //unacceptable entries try {//from w w w . ja va 2s . c o m this.sp = Float.parseFloat(jTextField1.getText()); this.ts = Float.parseFloat(jTextField2.getText()); this.ms = Long.parseLong(jTextField3.getText()); this.ic = Float.parseFloat(jTextField4.getText()); this.nmm = Integer.parseInt(jTextField7.getText()); this.ntf = Integer.parseInt(jTextField8.getText()); this.nc = Integer.parseInt(jTextField9.getText()); this.nlt = Integer.parseInt(jTextField10.getText()); this.smm = Float.parseFloat(jTextField11.getText()); this.stf = Float.parseFloat(jTextField12.getText()); this.sc = Float.parseFloat(jTextField13.getText()); this.slt = Float.parseFloat(jTextField14.getText()); jLabel31.setText(""); } catch (NumberFormatException e) { validEntry = false; jLabel31.setText("Invalid Entry!"); } //Check number of agents allows agent state display or not if ((this.nmm + this.ntf + this.nc + this.nlt) <= 100) this.displayAgentStates = true; else this.displayAgentStates = false; //Check the split of agents is acceptable if ((this.smm + this.stf + this.sc + this.slt) != 100) { //if not default to 70/10/10/10 this.smm = 0.7f; this.stf = 0.1f; this.sc = 0.1f; this.slt = 0.1f; } else { this.smm = (smm / 100); this.stf = (stf / 100); this.sc = (sc / 100); this.slt = (slt / 100); } //To pass the broker on initialisation int[] agentNums = { this.nmm, this.ntf, this.nc, this.nlt }; float[] agentSplit = { this.smm, this.stf, this.sc, this.slt }; //If the initial capital is less than the market size * starting price, //make the initial capital an acceptable value. if (this.ic < this.ms * this.sp) this.ic = this.ms * this.sp; //Before the simulation can start, an initial volatility is set: float volatility; Random rand = new Random(); volatility = rand.nextFloat() * (1f - 0.8f) + 0.8f; if (validEntry) { //start simulation; disable input here; jButton2.setEnabled(false); //jButton1.setEnabled(false); jButton4.setEnabled(true); this.broker = new Brokerage(this.sp, this.ic, this.mt, this.ms, this.ts, volatility, agentNums, agentSplit); this.time = 1; this.broker.runFirstStep(); setNewGUIState(); this.time = 2; } }
From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java
private void createBiomes() { if (graph == null) { return;//from w ww .ja va 2s. c om } //assign temperatures for (Graph.Corner c : graph.corners) { c.temperature = c.elevation; c.temperature *= c.temperature; c.temperature = 1 - c.temperature; } assignCenterTemperature(); //create random rivers Random rand = new Random(seed * 3); for (Graph.Corner c : graph.corners) { c.river = 0; } float riverProb = 0.2f; float riverStartHeight = 0.7f; int riverCounter = 0; corner: for (Graph.Corner c : graph.corners) { if (c.water || c.elevation < riverStartHeight) { continue; } if (rand.nextFloat() > riverProb) { continue; } if (c.river > 0) continue; for (Graph.Corner c2 : c.adjacent) { if (c2.river > 0) { continue corner; } for (Graph.Corner c3 : c2.adjacent) { if (c3.river > 0) { continue corner; } } } //start new river from here Graph.Corner current = c; current.river = Math.max(current.river, 1); while (!current.ocean && !current.coast) { float minH = current.elevation; Graph.Corner minC = null; for (Graph.Corner c2 : current.adjacent) { if (c2.river > 0 && c2.elevation < current.elevation) { minC = c2; //force closing of rivers break; } if (c2.elevation < minH) { minC = c2; minH = c2.elevation; } } if (minC == null) { LOG.warning("river stuck in a local minima without reaching the ocean"); break; } minC.river = Math.max(minC.river, current.river + 1); current = minC; } riverCounter++; } LOG.info("count of created rivers: " + riverCounter); showRivers = true; //assign moisture Queue<Graph.Corner> queue = new ArrayDeque<>(); for (Graph.Corner q : graph.corners) { if ((q.water || q.river > 0) && !q.ocean) { q.moisture = q.river > 0 ? Math.min(3.0f, (0.4f * q.river)) : 1; queue.add(q); } else { q.moisture = 0; } } while (!queue.isEmpty()) { Graph.Corner q = queue.poll(); for (Graph.Corner r : q.adjacent) { float newMoisture = q.moisture * 0.8f; if (newMoisture > r.moisture) { r.moisture = newMoisture; queue.add(r); } } } for (Graph.Corner q : graph.corners) { if (q.ocean || q.coast) { q.moisture = 1; } } //redistribute moisture ArrayList<Graph.Corner> corners = new ArrayList<>(); for (Graph.Corner q : graph.corners) { if (!q.ocean && !q.coast) { corners.add(q); } } Collections.sort(corners, new Comparator<Graph.Corner>() { @Override public int compare(Graph.Corner o1, Graph.Corner o2) { return Float.compare(o1.moisture, o2.moisture); } }); for (int i = 0; i < corners.size(); i++) { corners.get(i).moisture = i / (float) (corners.size() - 1); } assignCenterMoisture(); assignBiomes(); //update mesh updateTemperatureGeometry(); updateMoistureGeometry(); updateBiomesGeometry(); }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
private Object getPrimitiveValue(Type claz) { if (isPrimitive(claz)) { if (claz.equals(boolean.class) || claz.equals(Boolean.class)) { Random rand = new Random(); return rand.nextBoolean(); } else if (claz.equals(Date.class)) { return new Date(); } else if (claz.equals(Double.class) || claz.equals(double.class)) { Random rand = new Random(12345678L); return rand.nextDouble(); } else if (claz.equals(Float.class) || claz.equals(float.class)) { Random rand = new Random(12345678L); return rand.nextFloat(); } else if (claz.equals(String.class)) { return RandomStringUtils.randomAlphabetic(10); } else if (claz.equals(Long.class) || claz.equals(long.class) || claz.equals(Number.class)) { Random rand = new Random(); return new Long(rand.nextInt(123)); } else if (claz.equals(Integer.class) || claz.equals(int.class)) { Random rand = new Random(); return new Integer(rand.nextInt(123)); } else if (claz.equals(BigInteger.class)) { Random rand = new Random(); return new BigInteger(new BigInteger("1234567890123456789").bitLength(), rand); } else if (claz.equals(BigDecimal.class)) { Random rand = new Random(); return new BigDecimal(rand.nextInt(123)); } else if (claz.equals(Short.class) || claz.equals(short.class)) { Random rand = new Random(); return new Short((short) rand.nextInt(123)); }// w w w . ja v a 2s. com } return null; }
From source file:beproject.MainGUI.java
void createTagCloud() throws SQLException { TreeMap tmp = getFrequentWords(); Cloud cld = new Cloud(); JPanel tmpPanel = new JPanel(); FlowLayout t1 = new FlowLayout(); tmpPanel.setPreferredSize(new Dimension(512, 512)); tmpPanel.setLayout(t1);//from w w w. j av a2 s .c om tmpPanel.setBounds(0, 0, 512, 512); //FlowLayout lm=(FlowLayout) tmpPanel.getLayout(); for (int i = 0; i < 40 && !tmp.isEmpty(); i++) { Map.Entry mp = tmp.pollFirstEntry(); Tag t = new Tag((String) mp.getKey(), (int) (mp.getValue())); cld.addTag(t); } Random rand = new Random(); for (Tag tag : cld.tags()) { final JLabel label = new JLabel(tag.getName()); label.setOpaque(false); label.setFont(label.getFont().deriveFont(rand.nextFloat() * 39)); label.setForeground(new Color(rand.nextInt())); tmpPanel.add(label); } if (tagCloudPanel == null) { tagCloudPanel = new JScrollPane(tmpPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } else { jPanel3.remove(tagCloudPanel); jPanel3.validate(); tagCloudPanel = new JScrollPane(tmpPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } //tagCloudPanel.setLayout(new ScrollPaneLayout()); //tagCloudPanel.setAutoscrolls(true); tmpPanel.validate(); tagCloudPanel.validate(); jPanel3.add(tagCloudPanel, BorderLayout.CENTER); jPanel3.validate(); }
From source file:com.bluexml.xforms.generator.mapping.MappingGenerator.java
/** * Provides a dummy value for a specific type. * /* w w w. j a va 2 s . c o m*/ * @param type * @return */ @SuppressWarnings("unused") private String pickDummyValue(String type) { String[] strings = { "alpha", "beta", "gamma", "delta", "kappa", "sigma", "zeta", "omega", "everything", "something" }; if (type.equalsIgnoreCase("Date")) { return null; } Random alea = new Random(); if (type.equalsIgnoreCase("String")) { return strings[alea.nextInt(strings.length)]; } if (type.equalsIgnoreCase("boolean")) { if (alea.nextInt() % 2 == 0) { return "true"; } return "false"; } if (type.equalsIgnoreCase("int") || type.equalsIgnoreCase("integer")) { return "" + alea.nextInt(); } if (type.equalsIgnoreCase("float")) { return "" + alea.nextFloat(); } return null; }
From source file:org.eclipse.ecr.core.storage.sql.TestSQLBackend.java
public void testMoveMany() throws Exception { Session session = repository.getConnection(); Node root = session.getRootNode(); ArrayList<Node> nodes = new ArrayList<Node>(); nodes.add(root);/* www.j a va2 s.c o m*/ Random rnd = new Random(123456); List<String[]> graph = new ArrayList<String[]>(); for (int i = 0; i < 200; i++) { // create a node under a random node Node parent = nodes.get((int) Math.floor(rnd.nextFloat() * nodes.size())); Node child = session.addChildNode(parent, "child" + i, null, "TestDoc", false); nodes.add(child); // update graph addEdge(graph, parent.getId().toString(), child.getId().toString()); if ((i % 5) == 0) { // move a random node under a random parent int ip, ic; Node p, c; String pid, cid; do { ip = (int) Math.floor(rnd.nextFloat() * nodes.size()); ic = (int) Math.floor(rnd.nextFloat() * nodes.size()); p = nodes.get(ip); c = nodes.get(ic); pid = p.getId().toString(); cid = c.getId().toString(); if (isUnder(graph, cid, pid)) { // check we have an error for this move try { session.move(c, p, c.getName()); fail("shouldn't be able to move"); } catch (Exception e) { // ok } ic = 0; // try again } } while (ic == 0 || ip == ic); String oldpid = c.getParentId().toString(); session.move(c, p, c.getName()); removeEdge(graph, oldpid, cid); addEdge(graph, pid, cid); } } session.save(); // dumpGraph(graph); // dumpDescendants(buildDescendants(graph, root.getId().toString())); }
From source file:cobweb.Cobweb.java
/** * Add a new node with default values to the particle system *//* w ww . j a v a2 s . c o m*/ public void addNodeByButton() { String id = "new1"; for (int i = 1; i < MAX_INT; ++i) if (!particleSys.containsNode("new" + i)) { id = "new" + i; break; } String name = id; Node n = particleSys.makeNode(id, name, null, null, params.getServerAdress() + params.getPicturePath(), null, null); if (n != null) { for (int i = 0; i < particleSys.numberOfNodes(); ++i) { Node q = particleSys.getNode(i); if (n != q) particleSys.makeRepulsion(n, q, repulsionStrength, 20); } Random random = new Random(); n.getPosition().set(width / 2 - translateMouseX + (random.nextFloat() * NODE_SIZE * 6 - NODE_SIZE * 3), height / 2 - translateMouseY + (random.nextFloat() * NODE_SIZE * 6 - NODE_SIZE * 3)); n.fix(); particleSys.deselectAllNodes(); selectNode(n); } }
From source file:cobweb.Cobweb.java
/** * Handle events generated by the buttons in the GUI * //from w ww . ja va 2 s .c o m * @param button * The button event that was generated */ public void handleButtonEvents(GButton button) { if (!(displayPanel.isCollapsed() && graphPanel.isCollapsed())) { if (button == fixButton && button.eventType == GButton.CLICKED) { if (fixed) { for (int i = 0; i < particleSys.numberOfNodes(); ++i) particleSys.getNode(i).free(); } else { for (int i = 0; i < particleSys.numberOfNodes(); ++i) particleSys.getNode(i).fix(); } fixed = !fixed; } else if (button == smoothButton && button.eventType == GButton.CLICKED) { if (smoothButton.getText().equals(SMOOTH_BUTTON_FASTER_TEXT)) { smoothButton.setText(SMOOTH_BUTTON_NICER_TEXT); noSmooth(); } else { smoothButton.setText(SMOOTH_BUTTON_FASTER_TEXT); smooth(); } } else if (button == selectCommonNeighboursButton && button.eventType == GButton.CLICKED) { selectCommonNeighboursOfSelectedNodes(); } else if (button == selectNeighboursButton && button.eventType == GButton.CLICKED) { selectALLNeighboursOfSelectedNodes(); } else if (button == statisticsButton && button.eventType == GButton.CLICKED) { showStatistics(); } else if (button == onePathButton && button.eventType == GButton.CLICKED) { showOnePath(); } else if (button == allPathButton && button.eventType == GButton.CLICKED) { showAllPath(); } else if (button == invertButton && button.eventType == GButton.CLICKED) { invertSelection(); } else if (button == addNodeButton && button.eventType == GButton.CLICKED) { addNodeByButton(); } else if (button == addEdgeButton && button.eventType == GButton.CLICKED) { addEdgeByButton(); } else if (button == shuffleButton && button.eventType == GButton.CLICKED) { Random rand = new Random(); for (int i = 0; i < particleSys.numberOfNodes(); ++i) { particleSys.getNode(i).free(); particleSys.getNode(i).setPosition(new Vector2D(rand.nextFloat() + width / 2 - translateMouseX, rand.nextFloat() + height / 2 - translateMouseY)); } for (int i = 0; i < 2000; ++i) particleSys.tick(); fitNetworkInWindow(); } else if (button == relaxButton && button.eventType == GButton.CLICKED) { for (int i = 0; i < 2000; ++i) particleSys.tick(); } else if (button == fitButton && button.eventType == GButton.CLICKED) { fitNetworkInWindow(); } } }
From source file:org.languagetool.rules.spelling.SuggestionsChangesTest.java
/*** * TODO: document// w ww . ja v a 2 s .c o m * @throws IOException */ @Test public void testChanges() throws IOException { String correctionsFileLocation = System.getProperty("correctionsFileLocation"); assertNotEquals("needs corrections data", null, correctionsFileLocation); String testMode = System.getProperty("suggestionsTestMode"); assertThat(testMode, is(anyOf(equalTo("A"), equalTo("B"), equalTo("AB")))); if (testMode.equals("A") || testMode.equals("B")) { String modeValue = testMode.equals("A") ? "0" : "1"; System.setProperty("SuggestionsChangesTestAlternativeEnabled", modeValue); } String languagesValue = System.getProperty("languages"); Set<Language> languages = new HashSet<>(); if (languagesValue == null) { // default -> all languages languages.addAll(Languages.get()); } else { for (String langCode : languagesValue.split(",")) { languages.add(Languages.getLanguageForShortCode(langCode)); } } Random sampler = new Random(0); final float SAMPLE_RATE = 1f; Map<String, JLanguageTool> ltMap = new HashMap<>(); Map<String, Rule> rules = new HashMap<>(); final AtomicInteger numOriginalCorrect = new AtomicInteger(0), numReorderedCorrect = new AtomicInteger(0), numOtherCorrect = new AtomicInteger(0), numBothCorrect = new AtomicInteger(0), numMatches = new AtomicInteger(0), numCorrectSuggestion = new AtomicInteger(0), numTotal = new AtomicInteger(0); Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (testMode.equals("AB")) { System.out.printf( "%n**** Correct Suggestions ****%nBoth: %d / Original: %d / Reordered: %d / Other: %d%n", numBothCorrect.intValue(), numOriginalCorrect.intValue(), numReorderedCorrect.intValue(), numOtherCorrect.intValue()); int total = numOriginalCorrect.intValue() + numReorderedCorrect.intValue() + numOtherCorrect.intValue() + numBothCorrect.intValue(); float accuracyA = (float) (numBothCorrect.intValue() + numOriginalCorrect.intValue()) / total; float accuracyB = (float) (numBothCorrect.intValue() + numReorderedCorrect.intValue()) / total; System.out.printf("**** Accuracy ****%nA: %f / B: %f%n", accuracyA, accuracyB); } else { String name = testMode.equals("A") ? "Original" : "Alternative"; int correct = numCorrectSuggestion.intValue(); int total = numTotal.intValue(); float percentage = 100f * ((float) correct / total); System.out.printf("%n**** Correct Suggestions ****%n %s: %d / %d (%f%%)%n", name, correct, total, percentage); } })); try (CSVParser parser = new CSVParser(new FileReader(correctionsFileLocation), CSVFormat.DEFAULT.withFirstRecordAsHeader())) { for (CSVRecord record : parser) { if (sampler.nextFloat() > SAMPLE_RATE) { continue; } String lang = record.get("language"); String covered = record.get("covered"); String replacement = record.get("replacement"); //String sentenceStr = record.get("sentence"); if (lang.equals("auto")) { continue; // TODO do language detection? } Language language = Languages.getLanguageForShortCode(lang); if (!languages.contains(language)) { continue; } JLanguageTool lt = ltMap.computeIfAbsent(lang, langCode -> { try { JLanguageTool tool = new JLanguageTool(language); tool.activateLanguageModelRules(new File("ngrams/")); return tool; } catch (IOException e) { throw new RuntimeException(e); } }); Rule spellerRule = rules.computeIfAbsent(lang, langCode -> lt.getAllRules().stream() .filter(Rule::isDictionaryBasedSpellingRule).findFirst().orElse(null)); if (spellerRule == null) { continue; } numMatches.incrementAndGet(); //AnalyzedSentence sentence = lt.getAnalyzedSentence(sentenceStr); AnalyzedSentence sentence = lt.getAnalyzedSentence(covered); if (testMode.equals("AB")) { System.setProperty("SuggestionsChangesTestAlternativeEnabled", "0"); RuleMatch[] originalMatches = spellerRule.match(sentence); System.setProperty("SuggestionsChangesTestAlternativeEnabled", "1"); RuleMatch[] alternativeMatches = spellerRule.match(sentence); assertEquals(originalMatches.length, alternativeMatches.length); for (int i = 0; i < originalMatches.length; i++) { RuleMatch original = originalMatches[i]; RuleMatch alternative = alternativeMatches[i]; String matchedWord = sentence.getText().substring(original.getFromPos(), original.getToPos()); String matchedWord2 = sentence.getText().substring(alternative.getFromPos(), alternative.getToPos()); assertEquals(matchedWord, matchedWord2); if (!matchedWord.equals(covered)) { //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered); continue; } List<String> originalSuggestions = original.getSuggestedReplacements(); List<String> alternativeSuggestions = alternative.getSuggestedReplacements(); if (originalSuggestions.size() == 0 || alternativeSuggestions.size() == 0) { continue; } String firstOriginal = originalSuggestions.get(0); String firstAlternative = alternativeSuggestions.get(0); if (firstOriginal.equals(firstAlternative)) { if (firstOriginal.equals(replacement)) { numBothCorrect.incrementAndGet(); } else { numOtherCorrect.incrementAndGet(); } System.out.println("No change for match: " + matchedWord); } else { String correct; if (firstOriginal.equals(replacement)) { numOriginalCorrect.incrementAndGet(); correct = "A"; } else if (firstAlternative.equals(replacement)) { numReorderedCorrect.incrementAndGet(); correct = "B"; } else { numOtherCorrect.incrementAndGet(); correct = "other"; } System.out.printf( "Ordering changed for match %s, before: %s, after: %s, choosen: %s, correct: %s%n", matchedWord, firstOriginal, firstAlternative, replacement, correct); } } } else { RuleMatch[] matches = spellerRule.match(sentence); for (RuleMatch match : matches) { String matchedWord = sentence.getText().substring(match.getFromPos(), match.getToPos()); if (!matchedWord.equals(covered)) { //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered); continue; } List<String> suggestions = match.getSuggestedReplacements(); if (suggestions.size() == 0) { continue; } String first = suggestions.get(0); numTotal.incrementAndGet(); System.out.printf("Correction for %s: %s %s / chosen: %s -> position %d%n", covered, first, suggestions.subList(1, Math.min(suggestions.size(), 5)), replacement, suggestions.indexOf(replacement)); if (first.equals(replacement)) { numCorrectSuggestion.incrementAndGet(); } } } } } }