Skip to content

Chapter 3.1.2 Exercise 3.5 Solution #619

@Zxun2

Description

@Zxun2

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

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions