欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Hadoop 下 Pi 值的 MapReduce 实现

最编程 2024-03-02 16:43:15
...
package mapreduce1; /* * @create by 刘大哥 * 2019年9月3日 * 利用MapReduce计算pi值 * */ import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import PI.Pi; public class WordCount { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Job job = Job.getInstance(); job.setJobName("WordCount"); job.setJarByClass(WordCount.class); job.setMapperClass(doMapper.class); job.setReducerClass(doReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); Path in = new Path("hdfs://192.168.100.129:9000/user/hadoop/p1i.txt"); //输入路径 Path out = new Path("hdfs://192.168.100.129:9000/user/hadoop/out_pi1"); //输出路径 FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, out); System.exit(job.waitForCompletion(true) ? 0 : 1); } public static class doMapper extends Mapper<Object, Text, Text, IntWritable>{ private static final IntWritable one = new IntWritable(1); @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String word = line.toString(); //读取每个map的数值 //System.out.println(word); int num = Integer.parseInt(word); //转化为int类型 //System.out.println(num); int[] base = {2,5}; Pi test = new Pi(base); int a= 0; // 是否在扇形区域内的标志符 1:在扇形区域内 2:不在扇形区域内 int count = 0; // 统计在扇形区域内点的个数 for(int x = 0; x < num; x++){ double[] t = test.getNext(); if(t[0]*t[0]+t[1]*t[1]<1) { //在扇形区域内 a=1; count++; //在扇形区域内的个数加+ } else { //不在扇形区域内 a=2; } } double result= count*4.00000000/num; //每个map计算出pi的值 String strresule = String.valueOf(result); Text textresult = new Text(); /*转换类型为Text */ textresult.set(strresule); context.write(textresult, one); //写入 } } public static class doReducer extends Reducer<Text, IntWritable, Text, IntWritable>{ //reduce 整合输出 private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } result.set(sum); context.write(key, result); } } }

推荐阅读