该代码应该找到一个随机整数的标准偏差ArrayList.但是,我的标准偏差代码没有显示正确的结果.它显示了预期的另一个数字.
我究竟做错了什么?
import java.io.*;
import java.util.*;
public class Assignment4 {
public static void main(String[] args)
{
ArrayList<Integer> values = new ArrayList<Integer>();
int count = 0;
int total = 0;
Random r = new Random();
for (int i = 1; i <= 10; i++) {
values.add(r.nextInt(90)+ 1);
System.out.println(values);
}
System.out.println(mean(values));
System.out.println(sd(values));
}
public static double mean (ArrayList<Integer> table)
{
int total = 0;
for ( int i= 0;i < table.size(); i++)
{
int currentNum = table.get(i);
total+= currentNum;
}
return total/table.size();
}
public static double sd (ArrayList<Integer> table)
{
double mean= mean(table);
double temp =0;
for ( int i= 0; i <table.size(); i++)
{
temp= Math.pow(i-mean, 2);
}
return Math.sqrt(mean( table));
}
public static void selectionSort(ArrayList<Integer> table)
{
int count = table.size();
for(int pos = 0; pos < count - 1; pos++)
{
int locMin = pos;
for(int i = pos + 1; i < count; i++)
{
if(table.get(i) < table.get(locMin))
locMin = i;
}
int temp = table.get(pos);
table.set(pos, table.get(locMin) );
table.set(locMin, temp);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的标准偏差计算有错误:
这是查找标准差的算法:
Step 1: Find the mean.
Step 2: For each data point, find the square of its distance to the mean.
Step 3: Sum the values from Step 2.
Step 4: Divide by the number of data points.
Step 5: Take the square root.
Run Code Online (Sandbox Code Playgroud)
因此,您的代码应如下所示:
public static double sd (ArrayList<Integer> table)
{
// Step 1:
double mean = mean(table);
double temp = 0;
for (int i = 0; i < table.size(); i++)
{
int val = table.get(i);
// Step 2:
double squrDiffToMean = Math.pow(val - mean, 2);
// Step 3:
temp += squrDiffToMean;
}
// Step 4:
double meanOfDiffs = (double) temp / (double) (table.size());
// Step 5:
return Math.sqrt(meanOfDiffs);
}
Run Code Online (Sandbox Code Playgroud)
注意:您的平均值计算精度会有所下降.
你有:
return total/table.size();
Run Code Online (Sandbox Code Playgroud)
它应该是:
return (double) total / (double) table.size();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5484 次 |
| 最近记录: |