find the volume of a regular polygon circumscribed around a pyramid in php

To find the volume of a regular pyramid, we need to know the area of its base and the height of the pyramid. To find the area of the base of the pyramid, we can use the formula for the area of a regular polygon.

main.php
function getRegularPolygonArea($n, $s) {
  // $n is the number of sides
  // $s is the length of each side
  
  $apothem = $s / (2 * tan(pi() / $n));
  $area = ($n * $s * $apothem) / 2;
  return $area;
}
204 chars
9 lines

Once we have the area of the regular polygon, we can find the height of the pyramid using the Pythagorean theorem.

main.php
function getPyramidHeight($n, $s, $h) {
  $apothem = $s / (2 * tan(pi() / $n));
  $baseSide = 2 * $apothem;
  $baseRadius = $s / (2 * sin(pi() / $n));
  $slantHeight = sqrt(pow($h, 2) + pow($baseRadius, 2));
  
  return $slantHeight;
}
236 chars
9 lines

Finally, we can plug these values into the formula for the volume of a pyramid.

main.php
function getRegularPyramidVolume($n, $s, $h) {
  $area = getRegularPolygonArea($n, $s);
  $height = getPyramidHeight($n, $s, $h);
  $volume = ($area * $height) / 3;
  
  return $volume;
}
188 chars
8 lines

Calling getRegularPyramidVolume(4, 6, 8) with parameters for a regular square pyramid with a side length of 6 and a height of 8 would return the volume of the pyramid.

gistlibby LogSnag