×

Java program to calculate the mean, variance, and standard deviation of real numbers

Given an array of real numbers, we have to calculate the mean, variance, and standard deviation of real numbers.
Submitted by Nidhi, on February 28, 2022

Problem statement

In this program, we will calculate the mean, variance, and standard deviation of real numbers for the given number of floating-point values.

Java program to calculate the mean, variance, and standard deviation of real numbers

The source code to calculate the mean, variance and standard deviation of real numbers is given below. The given program is compiled and executed successfully.

```// Java program to calculate the mean, variance, and
// standard deviation of real numbers

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
double[] arr = new double[] {12.5, 14.5, 13.2, 8.95, 17.89};

double sum = 0;
double mean = 0;
double variance = 0;
double deviation = 0;

int i = 0;

for (i = 0; i < 5; i++)
sum = sum + arr[i];

mean = sum / 5;

sum = 0;
for (i = 0; i < 5; i++) {
sum = sum + Math.pow((arr[i] - mean), 2);
}
variance = sum / 5;

deviation = Math.sqrt(variance);

System.out.printf("Mean of elements    : %.2f\n", mean);
System.out.printf("variance of elements: %.2f\n", variance);
System.out.printf("Standard deviation  : %.2f\n", deviation);
}
}
```

Output

```Mean of elements    : 13.41
variance of elements: 8.40
Standard deviation  : 2.90
```

Explanation

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we created an array of float numbers. Then we calculated the mean, variance, and standard deviation of real numbers and printed the result.