-
Notifications
You must be signed in to change notification settings - Fork 131
Closed
Labels
Exercise solutionSolutions to textbook exercisesSolutions to textbook exercises
Description
Solution for Exercise 3.5
Noticed no solution is available for this exercise so I decided to contribute. Thanks!
Also, the solution seems to converge on the value 3. I wonder if this is intentional?
Link to exercise: https://sourceacademy.nus.edu.sg/sicpjs/3.1.2
function random(n) {
return math_floor(math_random() * n);
}
function random_in_range(low, high) {
const range = high - low;
return low + random(range);
}
function square(x){
return x*x;
}
function inside_circle(x, y, mid, rad){
return (square(x - head(mid)) +
square(y - tail(mid))) <= square(rad);
}
function estimate_integral(pred, x1, x2, y1, y2, trials) {
const area_rect = (x2 - x1) * (y2 - y1);
// monte-carlo
function monte(trials_remaining, trials_passed){
// Generate random coord
const x_coord = random_in_range(x1, x2);
const y_coord = random_in_range(y1, y2);
return trials_remaining === 0
? ( trials_passed / trials) * area_rect
: pred(x_coord, y_coord, mid_point, radius_cir)
? monte(trials_remaining - 1, trials_passed + 1)
: monte(trials_remaining - 1, trials_passed);
}
return monte(trials, 0) / square(radius_cir);
}
// test cases
const radius_cir = 3;
const mid_point = pair(3, 7);
estimate_integral(inside_circle, head(mid_point) - radius_cir,
head(mid_point) + radius_cir, tail(mid_point) - radius_cir,
tail(mid_point) + radius_cir, 10000);
Metadata
Metadata
Assignees
Labels
Exercise solutionSolutions to textbook exercisesSolutions to textbook exercises