Saturday 15 July 2017

Java Code to find out the Geometric Mean

Problem:

The geometric mean is used to measure central tendency. It is defined as

G.M = nth root of (x1 * x2 * x3 ......* xn)

Develop an algorithm to input n numbers and compute their geometric mean.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GeometricMean {

int n;
List<Double> numbers = new ArrayList<Double>();

public static void main(String[] args) {
GeometricMean geometricMean = new GeometricMean();
geometricMean.getTheNumbers();
System.out.println("the GM: " + geometricMean.findGM());
}

public void getTheNumbers(){
Scanner s = new Scanner(System.in);
System.out.println("how many numbers: ");
n = s.nextInt();
for(int i = 0; i<n; i++){
System.out.println("enter the numbers: ");
numbers.add(s.nextDouble());
}
s.close();
}

public double findGM(){
return Math.pow(findTheProductOfnumbers(), 1.0/n);
}

public double findTheProductOfnumbers(){
double product = 1.0;
for(Double n: numbers){
product = product * n;
}
return product;
}

}


Output:


how many numbers:
2
enter the numbers:
2
enter the numbers:
18
the GM: 6.0


how many numbers: 
3
enter the numbers: 
10
enter the numbers: 
51.2
enter the numbers: 
8
the GM: 15.999999999999998


how many numbers: 
5
enter the numbers: 
1
enter the numbers: 
3
enter the numbers: 
9
enter the numbers: 
27
enter the numbers: 
81
the GM: 9.000000000000002


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...