Programa para la media armónica de números

Dada una array de elementos, encuentre la media armónica de los números. 
Ejemplos: 
 

Input : arr[] = {2.0, 1.0}
Output : 1.3333
Harmonic mean = 2/(1/2.0 + 1/1.0)
             = (2 * 2)/3
             = 1.333

Input : arr[] = {13.5, 14.5, 14.8, 15.2, 16.1}
Output : 14.7707

La media armónica se usa cuando se requiere el promedio de tasas, a continuación se muestra la fórmula.
Media armónica de n números x 1 , x 2
x 3 , . . ., x n puede escribirse de la siguiente manera.
Media armónica = n / ((1/x 1 ) + (1/x 2 ) + (1/x 3 ) + . . . + (1/x n ))

 
A continuación se muestra la implementación de la media armónica. 
 

C++

// CPP program to find harmonic mean of numbers.
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns harmonic mean.
float harmonicMean(float arr[], int n)
{
    // Declare sum variables and initialize with zero.
    float sum = 0;
    for (int i = 0; i < n; i++)
        sum = sum + (float)1 / arr[i];
    return (float)n / sum;
}
 
// Driver code
int main()
{
    float arr[] = { 13.5, 14.5, 14.8, 15.2, 16.1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << harmonicMean(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// C program to find harmonic mean of numbers.
#include <stdio.h>
 
// Function that returns harmonic mean.
float harmonicMean(float arr[], int n)
{
    // Declare sum variables and initialize with zero.
    float sum = 0;
    for (int i = 0; i < n; i++)
        sum = sum + (float)1 / arr[i];
    return (float)n / sum;
}
 
// Driver code
int main()
{
    float arr[] = { 13.5, 14.5, 14.8, 15.2, 16.1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%f",harmonicMean(arr, n));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// JAVA program to find harmonic mean of numbers.
import java.io.*;
 
class GFG {
 
    // Function that returns harmonic mean.
    static float harmonicMean(float arr[], int n)
    {
        // Declare sum variables and initialize with zero
        float sum = 0;
        for (int i = 0; i < n; i++)
            sum = sum + (float)1 / arr[i];
        return (float)n / sum;
    }
 
    // Driver code
    public static void main(String args[])
    {
        float arr[] = { 13.5f, 14.5f, 14.8f, 15.2f, 16.1f };
        int n = arr.length;
        System.out.println(harmonicMean(arr, n));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Python3

# Python 3 program to find harmonic
# mean of numbers.
 
# Function that returns harmonic mean.
def harmonicMean(arr, n) :
   
    # Declare sum variables and
    # initialize with zero.
    sm = 0
    for i in range(0, n) :
        sm = sm + (1) / arr[i];
  
    return n / sm
 
 
# Driver code
arr = [ 13.5, 14.5, 14.8, 15.2, 16.1 ];
n = len(arr)
print(harmonicMean(arr, n))
 
# This code is contributed by Nikita Tiwari.

C#

// C# program to find harmonic
// mean of numbers.
using System;
 
class GFG {
 
    // Function that returns harmonic mean.
    static float harmonicMean(float[] arr, int n)
    {
        // Declare sum variables and
        // initialize with zero
        float sum = 0;
        for (int i = 0; i < n; i++)
            sum = sum + (float)1 / arr[i];
 
        return (float)n / sum;
    }
 
    // Driver code
    public static void Main()
    {
        float[] arr = { 13.5f, 14.5f, 14.8f,
                        15.2f, 16.1f };
        int n = arr.Length;
        Console.WriteLine(harmonicMean(arr, n));
    }
}
 
/*This code is contributed by vt_m.*/

PHP

<?php
// PHP program to find
// harmonic mean of numbers.
 
// Function that returns
// harmonic mean.
function harmonicMean($arr, $n)
{
     
    // Declare sum variables and
    // initialize with zero
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        $sum = $sum + (float)
               (1 / $arr[$i]);
 
    return (float)($n / $sum);
}
 
// Driver code
$arr = array(13.5, 14.5, 14.8, 15.2, 16.1);
$n = sizeof($arr);
echo(harmonicMean($arr, $n));
 
// This code is contributed by Ajit.
?>

Javascript

<script>
 
// Javascript program to find harmonic mean of numbers.
 
// Function that returns harmonic mean.
function harmonicMean(arr, n)
{
    // Declare sum variables and initialize
    // with zero.
    let sum = 0;
    for (let i = 0; i < n; i++)
        sum = sum + (1 / arr[i]);
 
    return n/sum;
}
 
// Driver code
 
let arr = [ 13.5, 14.5, 14.8, 15.2, 16.1 ];
let n = arr.length;
document.write(harmonicMean(arr, n));
 
</script>

Producción: 

14.7707

¿Qué pasa si nos dan elementos y sus frecuencias?  
Si nos dan n números y cada número tiene alguna frecuencia, simplemente usamos la fórmula 
Media armónica = (Frecuencia-Suma) /((f 1 /x 1 ) + (f 2 /x 2 ) + (f 3 /x 3 ) + . . . + (f n /x n )) 
Donde f 1 , f 2 , f 3 , . . ., f n son las frecuencias de los elementos y x 1 , 2 , x 3 , . . ., x n son los elementos de la array.
Frecuencia-Suma = f 1+ F 2 + F 3 , . . ., f n
Ejemplos: 
 

Input : num[] = {13, 14, 15, 16, 17}
        freq[] = {2, 5, 13, 7, 3}
Output : 15.0631

C++

// C++ program to find harmonic mean.
#include <bits/stdc++.h>
using namespace std;
// Function that returns harmonic mean.
float harmonicMean(int arr[], int freq[], int n)
{
    float sum = 0, frequency_sum = 0;
    for (int i = 0; i < n; i++) {
        sum = sum + (float)freq[i] / arr[i];
        frequency_sum  = frequency_sum  + freq[i];
    }
    return frequency_sum / sum;
}
 
// Driver code
int main()
{
    int num[] = { 13, 14, 15, 16, 17 };
    int freq[] = { 2, 5, 13, 7, 3 };
    int n = sizeof(num) / sizeof(num[0]);
    cout << harmonicMean(num, freq, n);
    return 0;
}

Java

// JAVA program to find harmonic mean.
 
class GFG {
     
    // Function that returns harmonic mean.
    static float harmonicMean(int arr[], int freq[],
                              int n)
    {
        float sum = 0, frequency_sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + (float)freq[i] / arr[i];
            frequency_sum  = frequency_sum  + freq[i];
        }
        return (frequency_sum / sum);
    }
      
    // Driver code
    public static void main(String args[])
    {
        int num[] = { 13, 14, 15, 16, 17 };
        int freq[] = { 2, 5, 13, 7, 3 };
        int n = num.length;
        System.out.println(harmonicMean(num, freq, n));
    }
}
 
/*This code is contributed by Nikita Tiwari.*/

Python3

# Python 3 program to find harmonic mean.
 
# Function that returns harmonic mean.
def harmonicMean(arr, freq, n) :
    sm = 0
    frequency_sum = 0
    for i in range(0,n) :
        sm = sm + freq[i] / arr[i]
        frequency_sum  = frequency_sum  + freq[i]
     
    return (round(frequency_sum / sm,4))
 
 
# Driver code
num = [ 13, 14, 15, 16, 17 ]
freq = [ 2, 5, 13, 7, 3 ]
n = len(num)
print (harmonicMean(num, freq, n))
 
 
# This code is contributed by Nikita Tiwari.

C#

// C# program to find harmonic mean.
using System;
 
class GFG {
 
    // Function that returns harmonic mean.
    static float harmonicMean(int[] arr, int[] freq,
                                              int n)
    {
        float sum = 0, frequency_sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + (float)freq[i] / arr[i];
            frequency_sum = frequency_sum + freq[i];
        }
        return (frequency_sum / sum);
    }
 
    // Driver code
    public static void Main()
    {
        int[] num = { 13, 14, 15, 16, 17 };
        int[] freq = { 2, 5, 13, 7, 3 };
        int n = num.Length;
        Console.WriteLine(harmonicMean(num, freq, n));
    }
}
 
/*This code is contributed by vt_m.*/

PHP

<?php
// PHP program to find
// harmonic mean.
 
// Function that returns
// harmonic mean.
function harmonicMean($arr, $freq, $n)
{
    $sum = 0; $frequency_sum = 0;
    for ($i = 0; $i < $n; $i++)
    {
        $sum = $sum + (float)
               ($freq[$i] / $arr[$i]);
        $frequency_sum = $frequency_sum +
                                $freq[$i];
    }
    return ($frequency_sum / $sum);
}
 
// Driver code
$num = array(13, 14, 15, 16, 17);
$freq = array(2, 5, 13, 7, 3);
$n = sizeof($num);
echo(harmonicMean($num, $freq, $n));
 
// This code is contributed by Ajit.
?>

Javascript

<script>
 
// Javascript program to find harmonic mean.
 
// Function that returns harmonic mean.
function harmonicMean(arr, freq, n)
{
    let sum = 0, frequency_sum = 0;
    for (let i = 0; i < n; i++) {
        sum = sum + (freq[i] / arr[i]);
        frequency_sum  = frequency_sum  + freq[i];
    }
    return frequency_sum / sum;
}
 
// Driver code
let num = [ 13, 14, 15, 16, 17 ];
let freq = [ 2, 5, 13, 7, 3 ];
let n = num.length;
document.write(harmonicMean(num, freq, n));
 
</script>

Producción: 

15.0631

Media armónica de números usando harmonic_mean() en Python: 
programa simple de Python para encontrar la media armónica usando la función harmonic_mean()
 

Python3

#'harmonic_mean()' new function added in 'Python3.6' onwards.
#Program calculates Harmonic Mean using harmonic_mean()
 
#imports Python statistics library
import statistics
def harmonic_mean():
    list= [13.5, 14.5, 14.8, 15.2, 16.1]
    print(statistics.harmonic_mean(list))
 
#Driver code
harmonic_mean()
 
 
#This code is contributed by 'Abhishek Agrawal'.
Output: 14.770680729373778

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 review-team@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 *