Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active December 27, 2015 15:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasdarimont/7351740 to your computer and use it in GitHub Desktop.
Save thomasdarimont/7351740 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