find the surface area of a regular polygon circumscribed around a sphere in javascript

To find the surface area of a regular polygon circumscribed around a sphere, we can use the following formula:

surface area = (number of sides * side length^2) / (4 * tangent(pi / number of sides))

where number of sides is the number of sides of the polygon, side length is the length of one side of the polygon, and tangent is a trigonometric function.

To calculate the side length, we can use the radius of the sphere r and the geometry of the polygon:

side length = 2 * r * sine(pi / number of sides)

Putting it all together, we can write the following JavaScript function:

index.tsx
function surfaceAreaRegularPolygonCircumscribedSphere(numSides, r) {
  const pi = Math.PI;
  const sideLength = 2 * r * Math.sin(pi / numSides);
  const surfaceArea = (numSides * sideLength**2) / (4 * Math.tan(pi / numSides));
  return surfaceArea;
}
251 chars
7 lines

We can then call this function with the number of sides and the radius of the circumscribed sphere as arguments:

index.tsx
const numSides = 6;
const radius = 10;
const surfaceArea = surfaceAreaRegularPolygonCircumscribedSphere(numSides, radius);
console.log(surfaceArea); // Output: 1031.2415506699096
179 chars
5 lines

gistlibby LogSnag