find the volume of a regular polygon circumscribed around a cylinder in go

To find the volume of a regular polygon circumscribed around a cylinder, we need to calculate the volume of the cylinder and the volume of the polygon and subtract the overlap.

First, let's calculate the volume of the cylinder. We need to know the height and radius of the cylinder.

main.go
func cylinderVolume(height, radius float64) float64 {
    return math.Pi * radius * radius * height
}
102 chars
4 lines

Next, we need to calculate the volume of the polygon. We can use the formula for the area of a regular polygon and multiply it by the height of the cylinder.

main.go
func polygonVolume(height, apothem float64, sides int) float64 {
    area := 0.5 * float64(sides) * apothem * apothem * math.Tan(2*math.Pi/float64(sides))
    return area * height
}
182 chars
5 lines

Finally, we need to calculate the overlap between the cylinder and the polygon. We can calculate the area of the base of the polygon and subtract it from the area of the base of the cylinder.

main.go
func overlapVolume(height, radius, apothem float64, sides int) float64 {
    baseArea := float64(sides) * apothem * apothem / (4 * math.Tan(math.Pi/float64(sides)))
    return baseArea * height - math.Pi * radius * radius * height
}
233 chars
5 lines

Now we can put it all together to find the volume of the regular polygon circumscribed around the cylinder.

main.go
func polygonCylinderVolume(height, radius, apothem float64, sides int) float64 {
    return cylinderVolume(height, radius) + polygonVolume(height, apothem, sides) - overlapVolume(height, radius, apothem, sides)
}
213 chars
4 lines

gistlibby LogSnag