Skip to content

Instantly share code, notes, and snippets.

@boostrack
Forked from thomasdarimont/LambdaPi.java
Last active September 21, 2015 07:15
Show Gist options
  • Save boostrack/ce42f0088144bf4822b6 to your computer and use it in GitHub Desktop.
Save boostrack/ce42f0088144bf4822b6 to your computer and use it in GitHub Desktop.
Approximate PI in almost one line with Lambdas in Java 8 :) - Theory here: http://www.stealthcopter.com/blog/2009/09/python-calculating-pi-using-random-numbers/
package de.tutorials.training.java8.lambda;
import java.util.stream.IntStream;
import static java.lang.Math.*;
import static java.util.concurrent.ThreadLocalRandom.*;
/**
* Author: Thomas Darimont
*/
public class LambdaPi {
public static void main(String[] args) {
int n = 9999999;
double pi = IntStream.range(0, n)
.map((a) -> sqrt(pow(current().nextDouble(),2)+pow(current().nextDouble(),2)) <= 1 ? 1 : 0)
.parallel()
.sum() * 4.0 / n;
System.out.printf("%s delta-abs: %s",pi, PI-pi);
}
}
package de.tutorials.training.java8.lambda;
import java.util.stream.IntStream;
import static java.lang.Math.*;
import static java.util.concurrent.ThreadLocalRandom.*;
/**
* Author: Thomas Darimont
*/
public class LambdaPi {
public static void main(String[] args) {
int n = 9999999;
double pi = IntStream.range(0, n)
.mapToDouble((a) -> 4.0 * 1.0 / n * (sqrt(pow(current().nextDouble(),2)+pow(current().nextDouble(),2)) <= 1 ? 1 : 0))
.parallel()
.sum();
System.out.printf("%s delta-abs: %s",pi, PI-pi);
}
}
package de.tutorials.training.java8.lambda;
import java.util.stream.IntStream;
import static java.lang.Math.*;
/**
* Author: Thomas Darimont
*/
public class LambdaPi {
public static void main(String[] args) {
int n = 999999;
double pi = IntStream.range(0,n)
.mapToDouble((a) -> 4.0 * 1.0 / n * (sqrt(pow(random(),2)+pow(random(),2)) <= 1 ? 1 : 0))
.sum();
System.out.printf("%s delta-abs: %s",pi, PI-pi);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment