java primer plus_Java Program to Calculate Standard Deviation

该程序演示了如何在Java中通过calculateSD()函数计算数组数据的标准偏差。输入为包含10个元素的数组,首先计算平均值,然后计算每个元素与平均值的差的平方,最后求平方差的平均值的平方根得到标准偏差。输出结果为2.872281。注意,这个程序计算的是样本标准偏差,如需计算总体标准偏差,需在calculateSD()方法中使用(n-1)代替n。
摘要由CSDN通过智能技术生成

In this program, you'll learn to calculate the standard deviation using a function in Java.

This program calculates the standard deviation of a individual series using arrays. Visit this page to learn about Standard Deviation.

To calculate the standard deviation, calculateSD() function is created. The array containing 10 elements is passed to the function and this function calculates the standard deviation and returns it to the main() function.

为了计算标准偏差,创建了calculateSD()函数。将包含10个元素的数组传递给该函数,此函数将计算标准偏差并将其返回给main()函数

Example: Program to Calculate Standard Deviation

public class StandardDeviation {

public static void main(String[] args) {

double[] numArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

double SD = calculateSD(numArray);

System.out.format("Standard Deviation = %.6f", SD);

}

public static double calculateSD(double numArray[])

{

double sum = 0.0, standardDeviation = 0.0;

int length = numArray.length;

for(double num : numArray) {

sum += num;

}

double mean = sum/length;

for(double num: numArray) {

standardDeviation += Math.pow(num - mean, 2);

}

return Math.sqrt(standardDeviation/length);

}

}

Note: This program calculates standard deviation of a sample. If you need to compute S.D. of a population, return Math.sqrt(standardDeviation/(length-1)) instead of Math.sqrt(standardDeviation/length) from the calculateSD() method.

When you run the program, the output will be:

Standard Deviation = 2.872281

In the above program, we've used the help of Math.pow() and Math.sqrt() to calculate the power and square root respectively.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值