Skip to content

Commit ec99172

Browse files
committed
Exercise 3.5 in 3.1.2: solution added; fixes #619
1 parent 9abd4b6 commit ec99172

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

xml/chapter3/section1/subsection2.xml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,35 @@ function random_in_range(low, high) {
591591
random_in_range(80000, 81000);
592592
</JAVASCRIPT>
593593
</SNIPPET>
594+
<SOLUTION>
595+
<SNIPPET HIDE="yes">
596+
<NAME>exercise_3_5_solution_example</NAME>
597+
<JAVASCRIPT>
598+
function inside_unit_circle(x, y) {
599+
return square(x) + square(y) &lt;= 1;
600+
}
601+
estimate_integral(inside_unit_circle, -1, 1, -1, 1, 50000);
602+
</JAVASCRIPT>
603+
</SNIPPET>
604+
<SNIPPET>
605+
<NAME>exercise_3_5_solution</NAME>
606+
<REQUIRES>square_definition</REQUIRES>
607+
<REQUIRES>monte_carlo</REQUIRES>
608+
<EXAMPLE>exercise_3_5_solution_example</EXAMPLE>
609+
<JAVASCRIPT>
610+
function random_in_range(low, high) {
611+
const range = high - low;
612+
return low + math_random() * range;
613+
}
614+
function estimate_integral(pred, x1, x2, y1, y2, trials) {
615+
const area_rect = (x2 - x1) * (y2 - y1);
616+
return monte_carlo(trials,
617+
() => pred(random_in_range(x1, x2),
618+
random_in_range(y1, y2))) * area_rect;
619+
}
620+
</JAVASCRIPT>
621+
</SNIPPET>
622+
</SOLUTION>
594623
</EXERCISE>
595624

596625
<EXERCISE>

0 commit comments

Comments
 (0)