Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

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

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:io.seldon.api.service.ABTestingServer.java

public static CFAlgorithm getUserTest(String consumer, String recTag, String clientUserId) {
    CFAlgorithm res = null;//from   www .j  a  v a  2  s .  c om
    final String abTestKey = getABTestKey(consumer, recTag);
    ABTest abTest = tests.get(abTestKey);
    if (abTest != null) {
        String mKey = MemCacheKeys.getABTestingUser(abTestKey, clientUserId,
                abTest.getAlgorithm().getAbTestingKey());
        Boolean inTest = (Boolean) MemCachePeer.get(mKey);
        if (inTest == null) {
            // decide whether this user should be in test and store in memcache
            if (Math.random() <= abTest.getPercentage()) {
                MemCachePeer.put(mKey, new Boolean(true), CACHING_TIME);
                res = abTest.getAlgorithm();
            } else {
                //Store the fact this user is not in the test
                MemCachePeer.put(mKey, new Boolean(false), CACHING_TIME);
            }
        } else if (inTest) {
            res = abTest.getAlgorithm();
        }

    }
    return res;
}

From source file:br.com.everson.clei.springmvc.controller.ClienteController.java

@RequestMapping("/salvarCadastroDeCliente")
public String persistirNovoCliente(Model m, Cliente c) {
    c.setId(Math.round(Math.random() * 10000));
    try {//  www  .j av  a  2 s .  c  o  m
        begin();
        getSession().save(c);
        commit();
    } catch (HibernateException e) {
        rollback();
        e.printStackTrace();
    }
    clientes.add(c);
    return "redirect:inicio";
}

From source file:lirmm.inria.fr.evaluation.Metrics.java

public static void evaluate(DataMatrix R, BigSparseRealMatrix U, BigSparseRealMatrix V) {
    OpenLongToDoubleHashMap rowsMAE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap rowsRMSE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap rowsT = new OpenLongToDoubleHashMap(0.0);
    //-------------------------------------------------------------------
    OpenLongToDoubleHashMap columnsMAE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap columnsRMSE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap columnsT = new OpenLongToDoubleHashMap(0.0);

    double RMSE = 0;
    double MAE = 0;
    double RMSERand = 0;
    double MAERand = 0;
    int k = 0;//  w  w w .j a v a2  s .c om
    for (OpenLongToDoubleHashMap.Iterator iterator = R.getTestSetEntries().iterator(); iterator.hasNext();) {
        k++;
        iterator.advance();
        final double value = iterator.value();
        final long key = iterator.key();
        final int i, j;
        i = (int) (key / R.getColumnDimension());
        j = (int) (key % R.getColumnDimension());
        //            double estimation = U.transpose().getRowVector(j).dotProduct(V.getColumnVector(j));
        double estimation = getDotProduct(U, i, V, j);
        RMSE += FastMath.pow(value - estimation, 2);
        MAE += FastMath.abs(value - estimation);
        double r = Math.random() * R.getMax();
        RMSERand += FastMath.pow(value - r, 2);
        MAERand += FastMath.abs(value - r);

        double v = rowsMAE.get(R.getRowNonZeroEntry(i));
        rowsMAE.put(R.getRowNonZeroEntry(i), v + FastMath.abs(value - estimation));
        v = rowsRMSE.get(R.getRowNonZeroEntry(i));
        rowsRMSE.put(R.getRowNonZeroEntry(i), v + FastMath.pow(value - estimation, 2));
        v = rowsT.get(R.getRowNonZeroEntry(i));
        rowsT.put(R.getRowNonZeroEntry(i), v + 1);

        v = columnsMAE.get(R.getColumnNonZeroEntry(j));
        columnsMAE.put(R.getColumnNonZeroEntry(j), v + FastMath.abs(value - estimation));
        v = columnsRMSE.get(R.getColumnNonZeroEntry(j));
        columnsRMSE.put(R.getColumnNonZeroEntry(j), v + FastMath.pow(value - estimation, 2));
        v = columnsT.get(R.getColumnNonZeroEntry(j));
        columnsT.put(R.getColumnNonZeroEntry(j), v + 1);
    }
    System.out.println("******************************************");
    for (OpenLongToDoubleHashMap.Iterator iterator = rowsMAE.iterator(); iterator.hasNext();) {
        iterator.advance();
        final long key = iterator.key();
        double localMAE = rowsMAE.get(key) / rowsT.get(key);
        double localRMSE = FastMath.sqrt(rowsRMSE.get(key) / rowsT.get(key));
        System.out.println(key + "\t" + (int) rowsT.get(key) + "\t" + localMAE + "\t" + localRMSE);
    }
    System.out.println("******************************************");
    for (OpenLongToDoubleHashMap.Iterator iterator = columnsMAE.iterator(); iterator.hasNext();) {
        iterator.advance();
        final long key = iterator.key();
        double localMAE = columnsMAE.get(key) / columnsT.get(key);
        double localRMSE = FastMath.sqrt(columnsRMSE.get(key) / columnsT.get(key));
        System.out.println(key + "\t" + (int) columnsT.get(key) + "\t" + localMAE + "\t" + localRMSE);
    }
    RMSE /= k;
    MAE /= k;
    RMSE = FastMath.sqrt(RMSE);
    RMSERand /= k;
    MAERand /= k;
    RMSERand = FastMath.sqrt(RMSERand);
    System.out.println("******************************************");
    System.out.println("Type\tMAE\tRMSE");
    System.out.println("DPMF\t" + MAE + "\t" + RMSE);
    System.out.println("Random\t" + MAERand + "\t" + RMSERand);
    System.out.println("******************************************");
}

From source file:tech.beshu.ror.integration.FieldLevelSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;/*from   ww  w .j  a va2  s  . com*/
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");

        String body = "{\"" + field + "\": \"" + docName + "\", \"dummy2\": true}";
        System.out.println("inserting: " + body);
        request.setEntity(new StringEntity(body));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        Thread.sleep(5000);

        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }

}

From source file:com.taobao.top.common.server.RefundMessageUrlKit.java

private static int getRandomNumber() {
    // 18?/*from www .j av a2s  .c o m*/
    int r = (int) Math.round(Math.random() * 7 + 1);
    return r;
}

From source file:utils.RandomVariable.java

/**
 * Generate a random string using the specified prefix and a fixed length.
 * @param prefix//  w  w  w . j  a v a  2 s. c  o m
 *        the specified string prefix.
 * @param length
 *        the length of the string to be appended.
 * @return random string.
 */
public static String randString(String prefix, int length) {
    StringBuilder result = new StringBuilder(prefix);
    for (int i = 0; i < length; i++) {
        char ch = (char) ((Math.random() * 26) + 97);
        result.append(ch);
    }

    return result.toString();
}

From source file:cv.mikusher.freechart.TimeSeries_AWT.java

private XYDataset createDataset() {
    final TimeSeries series = new TimeSeries("Random Data");
    Second current = new Second();
    double value = 100.0;
    for (int i = 0; i < 4000; i++) {
        try {//from   ww  w  . j a  va 2  s  . c o  m
            value = value + Math.random() - 0.5;
            series.add(current, new Double(value));
            current = (Second) current.next();
        } catch (SeriesException e) {
            System.err.println("Error adding to series");
        }
    }

    return new TimeSeriesCollection(series);
}

From source file:com.eyem.services.UsuarioService.java

public Usuario crearUsuario(String email, String nombre, String imagen, String imagenCover)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    Usuario u = new Usuario();
    u.setNombre(nombre);//from  w w w. j ava  2s. c  o m
    u.setEmail(email);
    u.setImagen(imagen);
    u.setImagenCover(imagenCover);
    String pass = ((int) (1000000 + Math.random() * 9000000)) + "";
    byte[] bytesOfMessage = pass.getBytes("UTF-8");
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] thedigest = md.digest(bytesOfMessage);
    String p = new String(thedigest);
    u.setPass(p);
    usuarioRepository.insert(u);
    return u;
}

From source file:Main.java

private ObservableList<XYChart.Series<String, Double>> getChartData() {
    double aValue = 1.56;
    double bValue = 1.06;
    ObservableList<XYChart.Series<String, Double>> answer = FXCollections.observableArrayList();
    Series<String, Double> aSeries = new Series<String, Double>();
    Series<String, Double> bSeries = new Series<String, Double>();
    aSeries.setName("a");
    bSeries.setName("b");

    for (int i = 2011; i < 2021; i++) {
        aSeries.getData().add(new XYChart.Data(Integer.toString(i), aValue));
        aValue = aValue + Math.random() - .5;
        bSeries.getData().add(new XYChart.Data(Integer.toString(i), bValue));
        bValue = bValue + Math.random() - .5;
    }//  w w  w .jav a 2s. c o  m
    answer.addAll(aSeries, bSeries);
    return answer;
}

From source file:blue.soundObject.PatternObjectTest.java

public void testClone() {
    PatternObject p = new PatternObject();
    p.addPattern(0);//from w ww  .  java2 s.  co m
    p.addPattern(0);
    p.addPattern(0);

    for (int i = 0; i < p.size(); i++) {
        Pattern pat = p.getPattern(i);

        for (int j = 0; j < pat.values.length; j++) {
            pat.values[j] = (Math.random() > 0.5d);
        }
    }

    SoundObject clone = (SoundObject) p.clone();

    boolean isEqual = EqualsBuilder.reflectionEquals(p, clone);

    if (!isEqual) {
        StringBuilder buffer = new StringBuilder();
        buffer.append("Problem with Pattern\n");
        buffer.append("Original Object\n");
        buffer.append(ToStringBuilder.reflectionToString(p)).append("\n");
        buffer.append("Cloned Object\n");
        buffer.append(ToStringBuilder.reflectionToString(clone)).append("\n");

        System.out.println(buffer.toString());

    }

    assertTrue(isEqual);

    assertEquals(p.saveAsXML(null).toString(), clone.saveAsXML(null).toString());
}