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

Here's a Ruby function that takes the number of sides of a regular polygon and the radius of its inscribing circle as arguments, and returns the area of the polygon:

main.rb
def area_of_polygon(num_sides, radius)
  apothem = radius * Math.cos(Math::PI / num_sides)
  length_of_side = 2 * radius * Math.sin(Math::PI / num_sides)
  area = 0.5 * num_sides * length_of_side * apothem
end
210 chars
6 lines

The formula for the area of a regular polygon is:

main.rb
area = 0.5 * num_sides * length_of_side * apothem
50 chars
2 lines

where num_sides is the number of sides of the polygon, length_of_side is the length of each side, and apothem is the distance from the center of the polygon to the midpoint of a side.

To calculate apothem and length_of_side, we can use the following formulas:

main.rb
apothem = radius * cos(pi / num_sides)

length_of_side = 2 * radius * sin(pi / num_sides)
90 chars
4 lines

where radius is the radius of the inscribed circle of the polygon, and pi is the mathematical constant.

Thus, the function uses the above formulas to compute apothem and length_of_side, plugs them into the formula for the area, and returns the result.

gistlibby LogSnag