Chinaunix首页 | 论坛 | 博客
  • 博客访问: 181973
  • 博文数量: 92
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1413
  • 用 户 组: 普通用户
  • 注册时间: 2013-02-04 21:12
文章分类
文章存档

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是非常不精确的,要想更精确则需要从头完成大的浮点类型  
阅读(740) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~