MOA 12.03
Real Time Analytics for Data Streams
MiscUtils.java
Go to the documentation of this file.
00001 /*
00002  *    MiscUtils.java
00003  *    Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
00004  *    @author Richard Kirkby ([email protected])
00005  *    @author Bernhard Pfahringer ([email protected])
00006  *
00007  *    This program is free software; you can redistribute it and/or modify
00008  *    it under the terms of the GNU General Public License as published by
00009  *    the Free Software Foundation; either version 3 of the License, or
00010  *    (at your option) any later version.
00011  *
00012  *    This program is distributed in the hope that it will be useful,
00013  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  *    GNU General Public License for more details.
00016  *
00017  *    You should have received a copy of the GNU General Public License
00018  *    along with this program. If not, see <http://www.gnu.org/licenses/>.
00019  *    
00020  */
00021 package moa.core;
00022 
00023 import java.io.PrintWriter;
00024 import java.io.StringWriter;
00025 import java.util.Random;
00026 
00027 import weka.core.Utils;
00028 
00036 public class MiscUtils {
00037 
00038     public static int chooseRandomIndexBasedOnWeights(double[] weights,
00039             Random random) {
00040         double probSum = Utils.sum(weights);
00041         double val = random.nextDouble() * probSum;
00042         int index = 0;
00043         double sum = 0.0;
00044         while ((sum <= val) && (index < weights.length)) {
00045             sum += weights[index++];
00046         }
00047         return index - 1;
00048     }
00049 
00050     public static int poisson(double lambda, Random r) {
00051         if (lambda < 100.0) {
00052             double product = 1.0;
00053             double sum = 1.0;
00054             double threshold = r.nextDouble() * Math.exp(lambda);
00055             int i = 1;
00056             int max = Math.max(100, 10 * (int) Math.ceil(lambda));
00057             while ((i < max) && (sum <= threshold)) {
00058                 product *= (lambda / i);
00059                 sum += product;
00060                 i++;
00061             }
00062             return i - 1;
00063         }
00064         double x = lambda + Math.sqrt(lambda) * r.nextGaussian();
00065         if (x < 0.0) {
00066             return 0;
00067         }
00068         return (int) Math.floor(x);
00069     }
00070 
00071     public static String getStackTraceString(Exception ex) {
00072         StringWriter stackTraceWriter = new StringWriter();
00073         ex.printStackTrace(new PrintWriter(stackTraceWriter));
00074         return "*** STACK TRACE ***\n" + stackTraceWriter.toString();
00075     }
00076 }
 All Classes Namespaces Files Functions Variables Enumerations