Media geométrica (dos métodos)

Dada una array de n elementos, necesitamos encontrar la media geométrica de los números. Generalmente, la media geométrica de n números es la raíz  enésima de su producto.
 

   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 

Ejemplos: 
 

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

Una solución simple es multiplicar primero todos los números y luego encontrar la (1/n)-ésima potencia de la multiplicación. 
 

C++

// Program to calculate the geometric mean
// of the given array elements.
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate geometric mean
// and return float value.
float geometricMean(int arr[], int n)
{
    // declare product variable and
    // initialize it to 1.
    float product = 1;
 
    // Compute the product of all the
    // elements in the array.
    for (int i = 0; i < n; i++)
        product = product * arr[i];
 
    // compute geometric mean through formula
    // pow(product, 1/n) and return the value
    // to main function.
    float gm = pow(product, (float)1 / n);
    return gm;
}
 
// Driver function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << geometricMean(arr, n);
    return 0;
}

Java

// Program to calculate the geometric mean
// of the given array elements.
import java.math.*;
 
class GFG{
     
    // function to calculate geometric mean
    // and return float value.
    static float geometricMean(int arr[], int n)
    {
        // declare product variable and
        // initialize it to 1.
        float product = 1;
 
        // Compute the product of all the
        // elements in the array.
        for (int i = 0; i < n; i++)
            product = product * arr[i];
 
        // compute geometric mean through
        // formula pow(product, 1/n) and
        // return the value to main function.
        float gm = (float)Math.pow(product, (float)1 / n);
        return gm;
    }
 
    // Driver function
    public static void main(String args[])
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int n = arr.length ;
        System.out.println(geometricMean(arr, n));
    }
}
 
/*This code is contributed by Nikita Tiwari*/

Python

# Python Program to calculate the
# geometric mean of the given
# array elements.
import math
 
# function to calculate geometric
# mean and return float value.
def geometricMean(arr, n) :
     
    # declare product variable and
    # initialize it to 1.
    product = 1
     
    # Compute the product of all the
    # elements in the array.
    for i in range(0,n) :
        product = product * arr[i]
  
    # compute geometric mean through
    # formula pow(product, 1/n) and
    # return the value to main function.
    gm = (float)(math.pow(product, (1 / n)))
    return (float)(gm)
     
     
# Driver function
arr = [ 1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
 
# to print 6 digits after decimal
print ('{0:.6f}'.format(geometricMean(arr, n)))
 
  
# This code is contributed by Nikita Tiwari

C#

// Program to calculate the geometric mean
// of the given array elements.
using System;
 
class GFG{
     
    // function to calculate geometric mean
    // and return float value.
    static float geometricMean(int []arr, int n)
    {
        // declare product variable and
        // initialize it to 1.
        float product = 1;
 
        // Compute the product of all the
        // elements in the array.
        for (int i = 0; i < n; i++)
            product = product * arr[i];
 
        // compute geometric mean through
        // formula pow(product, 1/n) and
        // return the value to main function.
        float gm = (float)Math.Pow(product, (float)1 / n);
        return gm;
    }
 
    // Driver function
    public static void Main()
    {
        int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int n = arr.Length ;
        Console.WriteLine(geometricMean(arr, n));
    }
}
 
/*This code is contributed by vt_m*/

PHP

<?php
// Program to calculate the geometric mean
// of the given array elements.
 
// function to calculate geometric mean
// and return float value.
function geometricMean($arr, $n)
{
     
    // declare product variable and
    // initialize it to 1.
    $product = 1;
 
    // Compute the product of all the
    // elements in the array.
    for ($i = 0; $i < $n; $i++)
        $product = $product * $arr[$i];
 
    // compute geometric mean through formula
    // pow(product, 1/n) and return the value
    // to main function.
    $gm = pow($product, (float)(1 / $n));
    return $gm;
}
 
// Driver Code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8);
$n = sizeof($arr);
echo(geometricMean($arr, $n));
 
// This code is contributed by Ajit.
?>

Javascript

<script>
// Javascript program to calculate the geometric mean
// of the given array elements.
 
    // function to calculate geometric mean
    // and return float value.
    function geometricMean(arr, n)
    {
        // declare product variable and
        // initialize it to 1.
        let product = 1;
   
        // Compute the product of all the
        // elements in the array.
        for (let i = 0; i < n; i++)
            product = product * arr[i];
   
        // compute geometric mean through
        // formula pow(product, 1/n) and
        // return the value to main function.
        let gm = Math.pow(product, 1 / n);
        return gm;
    }
   
// driver function
 
        let arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
        let n = arr.length ;
        document.write(geometricMean(arr, n));
    
   // This code is contributed by code_hunt.
</script>   

Producción: 
 

3.76435

La solución anterior simplemente provoca un desbordamiento. Una mejor solución es usar log. Hay n números y necesitamos calcular la media geométrica usando la fórmula: 

Geometric mean = Antilog((log(x1) + log(x2) +
                 log(x3) + . . . + log(xn))/n)  

Para calcular el Antilog en programación usamos la función exponente (exp())
 

C++

// Program to calculate the geometric mean
// of the given array elements.
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate geometric mean
// and return float value.
float geometricMean(int arr[], int n)
{
    // declare sum variable and
    // initialize it to 1.
    float sum = 0;
 
    // Compute the sum of all the
    // elements in the array.
    for (int i = 0; i < n; i++)
        sum = sum + log(arr[i]);
 
    // compute geometric mean through formula
    // antilog(((log(1) + log(2) + . . . + log(n))/n)
    // and return the value to main function.
    sum = sum / n;
 
    return exp(sum);
}
 
// Driver function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // function call
    cout << geometricMean(arr, n);
    return 0;
}

Java

// Java Program to calculate the geometric mean
// of the given array elements.
import java.io.*;
 
class GFG
{
     
    // function to calculate geometric mean
    // and return float value.
    static float geometricMean(int []arr, int n)
    {
        // declare sum variable and
        // initialize it to 1.
        float sum = 0;
     
        // Compute the sum of all the
        // elements in the array.
        for (int i = 0; i < n; i++)
            sum = sum + (float)Math.log(arr[i]);
     
        // compute geometric mean through formula
        // antilog(((log(1) + log(2) + . . . + log(n))/n)
        // and return the value to main function.
        sum = sum / n;
     
        return (float)Math.exp(sum);
    }
     
    // Driver function
    public static void main (String[] args)
    {
        int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int n = arr.length;
         
        // function call
        System.out.println(geometricMean(arr, n));
     
    }
}
 
// This code is contributed by vt_m.

Python3

# Program to calculate the
# geometric mean of the
# given array elements.
import math
 
# function to calculate
# geometric mean and
# return float value.
def geometricMean(arr, n):
     
    # declare sum variable and
    # initialize it to 1.
    sum = 0;
     
    # Compute the sum of all
    # the elements in the array.
    for i in range(n):
        sum = sum + math.log(arr[i]);
     
    # compute geometric mean
    # through formula antilog
    # (((log(1) + log(2) + . .
    # ... + log(n))/n)
    # and return the value to
    # main function.
    sum = sum / n;
     
    return math.exp(sum);
 
# Driver Code
arr= [ 1, 2, 3, 4, 5, 6, 7, 8 ];
n = len(arr);
 
# function call
print(geometricMean(arr, n));
 
# This code is contributed by mits.

C#

// Program to calculate the geometric mean
// of the given array elements.
using System;
 
class GFG {
 
    // function to calculate geometric mean
    // and return float value.
    static float geometricMean(int []arr, int n)
    {
        // declare sum variable and
        // initialize it to 1.
        float sum = 0;
     
        // Compute the sum of all the
        // elements in the array.
        for (int i = 0; i < n; i++)
            sum = sum + (float)Math.Log(arr[i]);
     
        // compute geometric mean through formula
        // antilog(((log(1) + log(2) + . . . + log(n))/n)
        // and return the value to main function.
        sum = sum / n;
     
        return (float)Math.Exp(sum);
    }
     
    // Driver function
    public static void Main ()
    {
        int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int n = arr.Length;
         
        // function call
        Console.WriteLine(geometricMean(arr, n));
     
    }
}
 
// This code is contributed by vt_m.

PHP

<?php
// Program to calculate the geometric mean
// of the given array elements.
 
// function to calculate geometric mean
// and return float value.
function geometricMean($arr, $n)
{
     
    // declare sum variable and
    // initialize it to 1.
    $sum = 0;
 
    // Compute the sum of all the
    // elements in the array.
    for($i = 0; $i < $n; $i++)
        $sum = $sum + log($arr[$i]);
 
    // compute geometric mean
    // through formula
    // antilog(((log(1) + log(2) +
    // . . . + log(n))/n)
    // and return the value
    $sum = $sum / $n;
 
    return exp($sum);
}
 
    // Driver Code
    $arr = array(1, 2, 3, 4, 5, 6, 7, 8);
    $n = count($arr);
     
    // function call
    echo geometricMean($arr, $n);
 
// This code is contributed by anuj_67.
?>

Javascript

<script>
 
// Program to calculate the geometric mean
// of the given array elements.
 
  
    // function to calculate geometric mean
    // and return float value.
     
    function geometricMean(arr, n)
    {
        // declare sum variable and
        // initialize it to 1.
        var sum = 0;
      
        // Compute the sum of all the
        // elements in the array.
        for (var i = 0; i < n; i++)
            sum = sum + Math.log(arr[i]);
      
        // compute geometric mean through formula
        // antilog(((log(1) + log(2) + . . . + log(n))/n)
        // and return the value to main function.
         
        sum = sum / n;
      
        return Math.exp(sum);
    }
      
    // Driver function
 
        var arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
        var n = arr.length;
          
        // function call
        document.write(geometricMean(arr, n).toFixed(5));
  
 // This code is contributed by bunnyram19.
</script>

Producción: 
 

3.76435

Este artículo es una contribución de Dharmendra Kumar . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a contribuido@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *