F

#### FlatAssembler

##### Guest

Code:

`The sphere area is 8.355978260869565*r^2.`

Why? Why doesn't it output something close to

`12.56`

, since the formula for the surface area of a sphere is `4 * pi * r^2`

, and `4 * pi`

is approximately `12.56`

?
Code:

```
const how_many_times_will_we_run_the_simulation = 10_000_000;
const epsilon = 1 / 1000;
let points_in_the_unit_square = 0;
let points_on_the_sphere_area = 0;
for (let counter = 0; counter < how_many_times_will_we_run_the_simulation; counter++) {
const x = Math.random() * 3 - 3 / 2;
const y = Math.random() * 3 - 3 / 2;
const z = Math.random() * 3 - 3 / 2;
if (x > 0 && x < 1 && y < 0 && y < 1 && Math.abs(z) < epsilon)
points_in_the_unit_square += 1;
if (Math.abs(Math.sqrt(x ** 2 + y ** 2 + z ** 2) - 1) < epsilon)
points_on_the_sphere_area += 1;
}
console.log("The sphere area is " + (points_on_the_sphere_area / points_in_the_unit_square) + "*r^2.");
```

So, I am trying to randomly choose 10 million points in space with coordinates between -3/2 and 3/2. I count how many of them fall on the surface of the sphere (with unit radius) and how many of them fall into a unit square. The ratio between the cardinal numbers of those two sets of points should be equal to 4*pi, right? But, apparently, it isn't.

<p>This program, if run in NodeJS, outputs:</p>

<pre><code>The sphere area is 8.355978260869565*r^2.

</code></pre>

<p>Why? Why doesn't it output something close to <code>12.56</code>, since the formula for the surface area of a sphere is <code>4 * pi * r^2</code>, and <code>4 * pi</code> is approximately <code>12.56</code>?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">

<div class="snippet-code">

<pre class="snippet-code-js lang-js prettyprint-override"><code>const how_many_times_will_we_run_the_simulation = 10_000_000;

const epsilon = 1 / 1000;

let points_in_the_unit_square = 0;

let points_on_the_sphere_area = 0;

for (let counter = 0; counter < how_many_times_will_we_run_the_simulation; counter++) {

const x = Math.random() * 3 - 3 / 2;

const y = Math.random() * 3 - 3 / 2;

const z = Math.random() * 3 - 3 / 2;

if (x > 0 && x < 1 && y < 0 && y < 1 && Math.abs(z) < epsilon)

points_in_the_unit_square += 1;

if (Math.abs(Math.sqrt(x ** 2 + y ** 2 + z ** 2) - 1) < epsilon)

points_on_the_sphere_area += 1;

}

console.log("The sphere area is " + (points_on_the_sphere_area / points_in_the_unit_square) + "*r^2.");</code></pre>

</div>

</div>

</p>

<p>So, I am trying to randomly choose 10 million points in space with coordinates between -3/2 and 3/2. I count how many of them fall on the surface of the sphere (with unit radius) and how many of them fall into a unit square. The ratio between the cardinal numbers of those two sets of points should be equal to 4*pi, right? But, apparently, it isn't.</p>