find the area of a regular polygon inscribed in a circle in javascript

To find the area of a regular polygon inscribed in a circle, you need to know the number of sides and the radius of the circle.

Here's the JavaScript code to calculate the area of the polygon:

index.tsx
function inscribedPolygonArea(sides, radius) {
  const centralAngle = 360 / (2 * sides);
  const apothem = radius * Math.cos((Math.PI / sides));
  const sideLength = 2 * radius * Math.sin((Math.PI / sides));
  const perimeter = sides * sideLength;
  const area = (perimeter * apothem) / 2;
  return area;
}

// usage example
const sides = 6;
const radius = 5;
const area = inscribedPolygonArea(sides, radius);
console.log(`Area of regular polygon with ${sides} sides inscribed in circle of radius ${radius} is ${area}.`);
522 chars
15 lines

In this code, we first calculate the central angle of the polygon using the formula 360 / (2 * sides). We then find the apothem (distance from center of the polygon to the midpoint of a side) using radius * Math.cos((Math.PI / sides)).

Next, we find the length of one side by using the formula 2 * radius * Math.sin((Math.PI / sides)). We can then find the perimeter of the polygon by multiplying the side length by the number of sides.

Finally, we use the formula (perimeter * apothem) / 2 to find the area of the polygon, and return it from the function.

By plugging in the number of sides and the radius, you can find the area of any regular polygon inscribed in a circle.

gistlibby LogSnag