Last active
December 27, 2015 15:59
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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