Horje
JavaScript Program to Find Geometric mean in G.P.

The geometric mean in a geometric progression (G.P.) is computed as the nth root of the product of all terms, where n is the number of terms. It provides a measure of central tendency in exponential sequences. This calculation is crucial in various mathematical and statistical analyses and we will see multiple approaches to do so.

If there are n elements x1, x2, x3, . . ., xn in an array and if we want to calculate the 
geometric mean of the array elements is Geometric mean = (x1 * x2 * x3 * . . . * xn)1/n

Examples: 

Input : arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output : 3.76435
= (1 * 2 * 3 * 4 * 5 * 6 * 7 * 8)1/8
= 403201/8
= 3.76435

Input : arr[] = {15, 12, 13, 19, 10}
Output : 13.447
= (15 * 12 * 13 * 19 * 10)1/5
= 4446001/5
= 13.477

Using Math.pow and Array.reduce

In this approach, we will calculate the geometric mean by first finding the product of all numbers in the array using Array.reduce, then applying the geometric mean formula using Math.pow.

Example: To demonstrate finding Geometric mean in G.P. using predefined methods in javascript.

JavaScript
function geometricMean(arr) {
    let product = arr.reduce((acc, curr) => acc * curr, 1);
    return Math.pow(product, 1 / arr.length);
}

// Example usage
let numbers = [4, 10, 16, 24];
let mean = geometricMean(numbers);
console.log('Geometric Mean:', mean);

Output
Geometric Mean: 11.132630734854963

Time Complexity: O(n) where n is size of given array

Auxiliary Space: O(1)

Using a For Loop

In this approach, we will find the geometric mean by iterating through the array and multiplying all elements to calculate the product, then applying the geometric mean formula to determine the mean value.

Example: To demonstrate finding Geometric mean in G.P. using for loop.

JavaScript
function geometricMean(arr) {
    let product = 1;
    for (let i = 0; i < arr.length; i++) {
        product *= arr[i];
    }
    return Math.pow(product, 1 / arr.length);
}

// Example usage
let numbers = [3, 9, 27, 81];
let mean = geometricMean(numbers);
console.log('Geometric Mean:', mean);

Output
Geometric Mean: 15.588457268119896

Time Complexity: O(n) where n is size of given array

Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Program to find nth term of Geometric Progression JavaScript Program to find nth term of Geometric Progression
How to Sort a Dictionary by Value in TypeScript ? How to Sort a Dictionary by Value in TypeScript ?
Find the Length Tuple in TypeScript ? Find the Length Tuple in TypeScript ?
How to Customize the Position of an Alert Box using JavaScript ? How to Customize the Position of an Alert Box using JavaScript ?
Difference Between Default &amp; Named Exports in JavaScript Difference Between Default &amp; Named Exports in JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19