hadoop自带的jar包计算圆周率pi

Hadoop中自带的hadoop-mapreduce-examples-2.7.6.jar含有一些事例,本文将用pi计算圆周率。若想了解其计算原理,参考:http://thinkinginhadoop.iteye.com/blog/710847

具体步骤如下:

1. 启动Hadoop

    切换到Hadoop安装目录下的sbin目录下执行./start-all.sh命令

    或执行./start-dfs.sh./start-yarn.sh两条命令

2. 使用hadoop-mapreduce-examples-2.7.6.jar计算圆周率

    hadoop jar ../share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.6.jar pi 10 10

    其中:第一个10是指运行10次map任务,第二个10是指每个map任务投掷次数,所以总投掷次数是10×10=100。

转载于:https://my.oschina.net/u/3902915/blog/1922907

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
串行化计算圆周率的方法是使用蒙特卡罗方法,即随机投点法。具体实现步骤如下: 1. 生成随机点:随机生成x、y坐标在0到1之间的点,共生成N个点。 2. 判断点是否在圆内:判断这N个点是否在以(0.5,0.5)为圆心,半径为0.5的圆内,如果在圆内,则计数器加1。 3. 计算圆周率:根据蒙特卡罗算法的原理,圆内点数与总点数的比例趋近于圆的面积与正方形面积的比例,即&pi;/4。因此,根据计数器的值可以计算出&pi;的近似值。 下面是一个使用Hadoop实现串行化计算圆周率的例子: 1. 创建输入文件input.txt,每行一个点,格式为"x,y"。 ``` 0.1,0.2 0.3,0.4 0.5,0.6 ... ``` 2. 编写MapReduce程序。 Mapper阶段:读入每个点,判断是否在圆内,如果在圆内,则输出"1,0",否则输出"0,1"。 Reducer阶段:将Mapper输出的结果累加,得到圆内点数和总点数,计算&pi;的近似值。 代码如下: Mapper: ```java public class PiMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> { private final static IntWritable one = new IntWritable(1); private final static IntWritable zero = new IntWritable(0); private final static double radius = 0.5; public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] coordinates = value.toString().split(","); double x = Double.parseDouble(coordinates[0]); double y = Double.parseDouble(coordinates[1]); if (Math.sqrt((x-0.5)*(x-0.5) + (y-0.5)*(y-0.5)) < radius) { context.write(one, zero); } else { context.write(zero, one); } } } ``` Reducer: ```java public class PiReducer extends Reducer<IntWritable, IntWritable, Text, NullWritable> { public void reduce(IntWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int inside = 0; int total = 0; for (IntWritable value : values) { inside += value.get(); total += 1; } double pi = 4.0 * inside / total; context.write(new Text("Pi is roughly " + pi), NullWritable.get()); } } ``` 3. 将程序打包成jar包并提交到Hadoop集群上运行。 ``` hadoop jar pi.jar Pi input.txt output ``` 4. 查看输出结果。 程序运行完毕后,在output目录下会生成一个名为part-r-00000的输出文件,其中包含了&pi;的近似值。 参考资料: [1] Hadoop MapReduce实现圆周率的计算. https://www.jianshu.com/p/ce8d80f0c1e0 [2] MapReduce计算圆周率. https://blog.csdn.net/guohongtao/article/details/19610591

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值