Emmanuel Akinfulubi

JavaScriptMath

Volume and surface area of a sphere in JavaScript

Intermediate · 4 min read

A ball, a planet, a soap bubble and a water droplet are all close to spheres. To know how much air a football holds or how much paint covers a dome, you need a sphere's volume and surface area. Both come from one measurement, the radius.

In this tutorial you will compute both for a sphere of radius 6, written two ways. Then you will check three facts that are exactly true in maths and see which of them survive in JavaScript. It is a lesson in why === is the wrong tool for comparing results that involve π. You need to know the area of a circle, arrow functions and ** for powers.

The two formulas

For a sphere of radius r:

  • Volume = 4/3 × π × r³
  • Surface area = 4 × π × r²

Divide one by the other and most of it cancels: volume ÷ surface = r / 3. For r = 6, that is exactly 2.

Three facts to test

Here are three things that are true in maths:

  1. Volume divided by surface area is r / 3.
  2. At r = 6, half a sphere (a hemisphere) has a volume of 2/3 × π × 216 = 144π, and the whole sphere's surface is 4 × π × 36 = 144π. The same number.
  3. A sphere is exactly two thirds of the smallest cylinder that holds it. That cylinder has the same radius and a height of 2r. The Greek mathematician Archimedes proved this more than 2,000 years ago.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

78 A sphere, and two formulas that should agree

fair

Give the volume and surface area of a sphere of radius 6, writing the volume as (4 / 3) * pi * r ** 3 and again as 4 * pi * r ** 3 / 3. Then check three relationships that hold exactly in mathematics, and see which survive in floating point.

Stuck? Three hints, smallest first
  1. 1. Volume is 4 / 3 pi r ** 3 and surface is 4 pi r ** 2, so volume over surface is r / 3.
  2. 2. At r = 6 a hemisphere's volume and the sphere's surface area are the same number.
  3. 3. Archimedes: a sphere is two thirds of the cylinder that just contains it.

Step 1: the volume, two ways

Step 1

const volumeThirdFirst = (r) => (4 / 3) * Math.PI * r ** 3;
const volumeDivideLast = (r) => (4 * Math.PI * r ** 3) / 3;
const r = 6;
console.log(volumeThirdFirst(r)); // 904.7786842338603
console.log(volumeDivideLast(r)); // 904.7786842338604

Same formula, written in two orders, and the last digit differs. 4/3 is 1.333…, which can't be stored exactly. Every multiplication and division also rounds its result to the nearest number JavaScript can store. The two orders round in different places, so they land on neighboring values.

Step 2: the surface area

Step 2

const surface = (r) => 4 * Math.PI * r ** 2;
console.log(surface(r)); // 452.3893421169302

Step 3: fact 1, volume over surface

Step 3

console.log(volumeThirdFirst(r) / surface(r)); // 1.9999999999999998
console.log(r / 3);                            // 2

It should be exactly 2. It comes out a hair below. The tiny roundings in the volume and the surface don't cancel out when you divide.

Step 4: fact 2, hemisphere and surface

Step 4

const hemisphereVolume = (r) => (2 / 3) * Math.PI * r ** 3;
console.log(hemisphereVolume(r) === surface(r));            // false
console.log(hemisphereVolume(r) - surface(r));              // -5.684341886080802e-14
console.log(Math.abs(hemisphereVolume(r) - surface(r)) < 1e-12); // true

They should be equal, and === says no. The hemisphere comes out smaller by about 0.00000000000006. Comparing the size of the difference with a small tolerance, here 1e-12, says what you really mean: "these are the same, give or take rounding".

Step 5: fact 3, Archimedes

Step 5

const boundingCylinder = Math.PI * r ** 2 * (2 * r);
console.log((2 / 3) * boundingCylinder);                       // 904.7786842338603
console.log(volumeThirdFirst(r) === (2 / 3) * boundingCylinder); // true

This one holds exactly, to the last digit. But nothing about the maths told us it would and the other two wouldn't. It depends only on where each expression happens to round.

So the safe rule is: never check a formula with === unless you have tried that exact expression, and even then a harmless rewrite can break it. Use a tolerance.

Step 6: the surface is how fast the volume grows

One more fact. If you make the radius a tiny bit bigger, the volume grows by about the surface area times that tiny bit. That makes sense: you are adding a thin skin all over the outside. We can check it by nudging the radius up and down by a small amount eps:

Step 6

const eps = 1e-6;
const derivative = (volumeThirdFirst(r + eps) - volumeThirdFirst(r - eps)) / (2 * eps);
console.log(Math.abs(derivative - surface(r)) < 1e-6); // true

This rate of change is called the derivative. It matches the surface area closely, but not exactly. Making eps much smaller doesn't help: the two volumes become so close that subtracting them loses most of their digits.

The full solution

The answer panel has both volume functions, surface, hemisphereVolume, the bounding cylinder and the numerical derivative, and prints the volume both ways, the surface, volume over surface against r / 3, the hemisphere against the surface with their difference, two thirds of the cylinder, and the derivative. Press Run to see the output.

The answer

const volumeThirdFirst = (r) => (4 / 3) * Math.PI * r ** 3;
const volumeDivideLast = (r) => (4 * Math.PI * r ** 3) / 3;
const surface = (r) => 4 * Math.PI * r ** 2;
const hemisphereVolume = (r) => (2 / 3) * Math.PI * r ** 3;

const r = 6;

// The cylinder that just contains the sphere: same radius, height 2r.
const boundingCylinder = Math.PI * r ** 2 * (2 * r);

// dV/dr should be the surface area. Check it numerically.
const eps = 1e-6;
const derivative = (volumeThirdFirst(r + eps) - volumeThirdFirst(r - eps)) / (2 * eps);

console.log('volume, 4/3 first  :', volumeThirdFirst(r));
console.log('volume, divide last:', volumeDivideLast(r), '<- one bit higher');
console.log('surface            :', surface(r));
console.log('volume / surface   :', volumeThirdFirst(r) / surface(r), 'should be r / 3 =', r / 3);
console.log('hemisphere volume  :', hemisphereVolume(r), 'against the surface', surface(r));
console.log('difference         :', hemisphereVolume(r) - surface(r));
console.log('two thirds of cyl  :', (2 / 3) * boundingCylinder);
console.log('dV/dr              :', derivative);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the volume is 904.7786842338603 with the 4 / 3 written first', volumeThirdFirst(r), 904.7786842338603);
test('and 904.7786842338604 if you divide at the end instead', [volumeDivideLast(r), volumeDivideLast(r) === volumeThirdFirst(r)], [904.7786842338604, false]);
test('the surface area is 452.3893421169302', surface(r), 452.3893421169302);
test('volume over surface should be r / 3, and comes out just under 2', [volumeThirdFirst(r) / surface(r), volumeThirdFirst(r) / surface(r) === r / 3], [1.9999999999999998, false]);
test('at r = 6 the hemisphere volume equals the surface area, in mathematics', Math.abs(hemisphereVolume(r) - surface(r)) < 1e-12, true);
test('in doubles they differ by 5.7e-14, so === would say no', hemisphereVolume(r) === surface(r), false);
test('Archimedes survives exactly: the sphere is two thirds of its cylinder', volumeThirdFirst(r) === (2 / 3) * boundingCylinder, true);
test('and the rate of change of volume with radius is the surface area', Math.abs(derivative - surface(r)) < 1e-6, true);

Three identities, three different fates. V / A = r / 3 comes out 1.9999999999999998 instead of 2. The hemisphere volume and the surface area, equal at exactly r = 6, differ by 5.7e-14. And Archimedes' result — a sphere is two thirds of the cylinder that just contains it — happens to hold bit for bit. Nothing about the mathematics predicts which; it depends on where each expression rounds.

So the rule for geometry code is the rule for all floating point: never assert an identity with === unless you have checked that specific expression, and even then a harmless-looking rewrite can break it. Math.abs(a - b) < 1e-12 states what you actually mean. The numerical derivative is the same idea from the other side: (V(r + h) - V(r - h)) / 2h matches the surface area to about 5e-8 rather than exactly, and shrinking h further makes it worse, not better, because the subtraction in the numerator starts cancelling.

Common mistakes

  • Writing 4 / 3 * Math.PI * r ** 2. Volume uses r³. Using r² gives a number with the wrong units.
  • Checking a formula with ===. Volume over surface is 1.9999999999999998, not 2. Compare with a tolerance.
  • Thinking a smaller eps is always more accurate. Past a point the subtraction cancels the digits you need, and the answer gets worse.

Try it yourself

  1. A football has a diameter of about 22 cm. Find its volume in liters (1 liter is 1000 cm³).
  2. Write radiusFromVolume(v) using Math.cbrt, and check that radiusFromVolume(volumeThirdFirst(6)) is close to 6.
  3. Try Step 6 with eps set to 1e-3, 1e-6 and 1e-10, and print how far each one is from surface(r).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.