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

To find the surface area of a regular polygon inscribed in a sphere, we can use the following formula:

Surface area = (number of sides * side length^2 * cot(pi/number of sides))

where cot is the cotangent function and pi is the mathematical constant pi.

Here's the Swift code to calculate the surface area of a regular polygon inscribed in a sphere:

main.swift
func surfaceAreaOfRegularPolygonInSphere(numberOfSides: Double, sideLength: Double) -> Double {
    let pi = Double.pi
    let cot = { 1.0 / tan($0) }
    return numberOfSides * pow(sideLength, 2) * cot(pi / numberOfSides)
}
225 chars
6 lines

You can then call this function with the number of sides and side length of your regular polygon as arguments:

main.swift
let numberOfSides = 6.0 // for a hexagon
let sideLength = 1.0
let surfaceArea = surfaceAreaOfRegularPolygonInSphere(numberOfSides: numberOfSides, sideLength: sideLength)
print(surfaceArea) // output: 7.794228634060309
218 chars
5 lines

So the surface area of a regular hexagon inscribed in a sphere with a side length of 1.0 would be approximately 7.79 square units.

gistlibby LogSnag