Swift Program to Find Geometric Mean of the Numbers



This tutorial will discuss how to write swift program to find the geometric mean of the numbers.

Geometric mean also known as GM. Geometric mean is defined as the xth root of the product of x numbers. Suppose we have x elements(that are, a1, a2, a3, ....ax) in the given array, then the geometric mean is −

GM = (a1 * a2 * a3 * a4 * ....*ax)1/x

Below is a demonstration of the same −

Input

Suppose our given input is −

MyVal = [34, 67, 2, 45, 8, 12]

Output

The desired output would be −

Geometric Mean = 16.413138687438

Explanation

(34 * 67 * 2 * 45 * 8 * 12)1/6 = (19681920)1/6 = 16.413138687438

Formula

Following is the formula for geometric mean −

GM = (a1 * a2 * a3 * a4 * ....*ax)1/x

Algorithm

Following is the algorithm −

  • Step 1 − Create an array.

  • Step 2 − Declare a variable to store the product of the elements.

  • Step 3 − Run a for loop from 0 to less than the size of the array. Or we can say iterate through each element and find their product.

for x in 0..<arrNums.count{
   sum += arrNums[x]
}
  • Step 4− Find the geometric mean by calculating the xth root of the product of x numbers.

var GeometricMean = pow(arrProduct, 1/size)
  • Step 5 − Print the output

Example 1

The following program shows how to find the geometric mean of the numbers.

import Foundation import Glibc // Creating array var MyNumber = [3.4, 5.6, 1.2, 4.0] // To store the product var arrProduct = 1.0 // Finding the product of all the numbers for y in 0..<MyNumber.count{ arrProduct = arrProduct * MyNumber[y] } var size = Double(MyNumber.count) // Finding the geometric mean var GeometricMean = pow(arrProduct, 1/size) print("Array:", MyNumber) print("Geometric Mean:", GeometricMean)

Output

Array: [3.4, 5.6, 1.2, 4.0]
Geometric Mean: 3.091911434311368

Example 2

The following program shows how to find the geometric mean of the numbers.

import Foundation import Glibc // Function to find the geometric mean func geoMean(arr: [Double])->Double{ let MyNumber = arr // To store the product var arrProduct = 1.0 // Finding the product of all the numbers for y in 0..<MyNumber.count{ arrProduct = arrProduct * MyNumber[y] } let size = Double(MyNumber.count) // Finding the geometric mean let GeometricMean = pow(arrProduct, 1/size) return GeometricMean } // Creating an array var Myval = [5.6, 8.9, 12.3, 5.6, 34.5] print("Array:", Myval) print("Geometric Mean:", geoMean(arr: Myval))

Output

Array: [5.6, 8.9, 12.3, 5.6, 34.5]
Geometric Mean: 10.344227262841542

Here, in the above code, we have an array named Myval of double type. Now to find the geometric mean of Myval, so we create a function named geoMean(). This function will return the geometric mean. So the resultant geometric mean is 10.344227262841542.


Advertisements