@@ -27,7 +27,6 @@ scaling up to the full circle, we have an estimate of pi.
2727
2828
2929
30-
3130{% highlight r %}
3231piR <- function(N) {
3332 x <- runif(N)
@@ -46,7 +45,6 @@ c(piR(1000), piR(10000), piR(100000), piR(1000000))
4645[1] 3.156 3.155 3.139 3.141
4746</pre >
4847
49-
5048The neat thing about Rcpp sugar enables us to write C++ code that
5149looks almost as compact.
5250
@@ -56,19 +54,19 @@ using namespace Rcpp;
5654
5755// [[ Rcpp::export]]
5856double piSugar(const int N) {
59- RNGScope scope; // ensure RNG gets set/reset
60- NumericVector x = runif(N);
61- NumericVector y = runif(N);
62- NumericVector d = sqrt(x* x + y* y);
63- return 4.0 * sum(d < 1.0) / N;
57+ NumericVector x = runif(N);
58+ NumericVector y = runif(N);
59+ NumericVector d = sqrt(x* x + y* y);
60+ return 4.0 * sum(d < 1.0) / N;
6461}
6562{% endhighlight %}
6663
67-
6864Apart from using types (hey, this is C++) and assuring the RNG gets
6965set and reset, the code is essentially identical.
7066
71- And by using the same RNG, so are the results.
67+ And by using the same RNG, so are the results. Rcpp ensures that
68+ the RNG state is set and reset properly by instantiating an object
69+ of class ` RNGScope ` .
7270
7371{% highlight r %}
7472set.seed(5)
@@ -80,4 +78,3 @@ c(piSugar(1000), piSugar(10000), piSugar(100000), piSugar(1000000))
8078<pre class =" output " >
8179[1] 3.156 3.155 3.139 3.141
8280</pre >
83-
0 commit comments