2013年(92)
分类: 信息化
2013-03-20 02:42:18
[代码] MapReduce的mainRunner忽略,咱们可根据需要改下输入输出KeyValue的意义 // Mapper
public class PieMapper extends
Mapper {
private Random random = new Random();
@Override
protected void map(IntWritable key, LongWritable value, Context context)
throws IOException, InterruptedException {
long inside = 0;
for (int i = 0; i < value.get(); i ) {
double a = random.nextDouble();
double b = random.nextDouble();
if ((a * a b * b) <= 1) {
inside ;
}
}
context.write(value, new LongWritable(inside));
}
}
// 输入为第几行(忽略) 本行所算的抛飞镖次数
// Reducer
public class PieReducer extends
Reducer {
@Override
protected void reduce(LongWritable key, Iterable values,
Context context) throws IOException, InterruptedException {
long total = 0;
long inside = 0;
for (LongWritable value : values) {
total = key.get();
inside = value.get();
}
context.write(key, new DoubleWritable(
4 * (inside / total)));
}
}
// 代码大约比较清楚,输出为抛的总次数所对应的算出的圆周率,可以用来对比抛N次所得到的精度。当然Double是非常不精确的,要想更精确则需要从头完成大的浮点类型