find the volume of a regular polygon inscribed in a sphere in swift

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

V = (2nr^3 tan(π/n)) / 3

where n is the number of sides of the polygon, and r is the radius of the sphere.

In Swift, we can write a function to calculate the volume using this formula:

main.swift
func volumeOfInscribedPolygon(sides n: Int, radius r: Double) -> Double {
    let numerator = 2 * Double(n) * pow(r, 3) * tan(Double.pi / Double(n))
    let denominator = 3.0
    return numerator / denominator
}
212 chars
6 lines

We can call this function and pass in the number of sides and radius of the sphere as parameters:

main.swift
let n = 6 // number of sides of regular polygon
let r = 5.0 // radius of sphere
let volume = volumeOfInscribedPolygon(sides: n, radius: r)
print(volume)
153 chars
5 lines

This will print out the volume of the regular polygon inscribed in the sphere with 6 sides and a radius of 5.0.

gistlibby LogSnag