集合串流 – stream

todo

蒙地卡羅求 π 值

底下的代碼可以利用 stream 特性,求請 π 值

package monte;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Monte {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Random rand=new Random();
        long batch=30_000_000L;
        var epochs=3000;
        double incircle=0;
        for(int epoch=1;epoch<=epochs;epoch++){
            Listx=rand
                    .doubles(batch)
                    .boxed()
                    .collect(Collectors.toCollection(ArrayList::new));
            x.replaceAll(n->n*n);
            Listy=rand
                    .doubles(batch)
                    .mapToObj(i->i*i)
                    .collect(Collectors.toCollection(ArrayList::new));
            Listdist=IntStream.range(0, x.size())
                    .mapToObj(i->Math.sqrt(x.get(i)+y.get(i)))
                    .filter(i->i<=1)
                    .collect(Collectors.toCollection(ArrayList::new));
            //dist.removeIf(n->n>1);
            incircle+=dist.size();
            var area=incircle/(epoch*batch);
            var pi=4*area;
            System.out.printf("Epoch:%03d, %.10f\n", epoch, pi);
        }
    }
}

todo

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *