find the surface area of a regular polygon inscribed in a sphere in ruby

To find the surface area of a regular polygon inscribed in a sphere, we need to find the area of each face of the polygon and then add them up.

Here's the code in Ruby using the Math module:

main.rb
def surface_area_of_polygon_in_sphere(n, r)
  # n is the number of sides of the polygon
  # r is the radius of the sphere
  
  # calculate the side length of the polygon
  side_length = 2 * r * Math.sin(Math::PI / n)
  
  # calculate the apothem of the polygon
  apothem = r * Math.cos(Math::PI / n)
  
  # calculate the area of each face
  area_of_face = (1.0 / 2) * side_length * apothem
  
  # calculate the total surface area
  total_surface_area = n * area_of_face

  return total_surface_area
end
503 chars
19 lines

To use this function, simply call it with the number of sides of the polygon (n) and the radius of the sphere (r) as arguments:

main.rb
n = 6     # for example, a regular hexagon
r = 1.0   # assume a sphere of radius 1.0

surface_area = surface_area_of_polygon_in_sphere(n, r)
puts "The surface area of the regular polygon inscribed in a sphere is #{surface_area} square units."
243 chars
6 lines

Output:

main.rb
The surface area of the regular polygon inscribed in a sphere is 10.392304845413264 square units.
98 chars
2 lines

gistlibby LogSnag