Java计算置信区间

时间:2015-05-20 04:55:21

标签: java confidence-interval

我正在寻找一种采用或不采用参数来计算置信区间的方法 我不想要apache方法, 这只是一个简单的方法或som类型的代码。

2 个答案:

答案 0 :(得分:4)

我的知识受到限制,它基本上归结为完成针对预期答案集的在线任务(https://www.hackerrank.com/challenges/stat-warmup)。

但是,据我所知,答案中有错误,我想纠正这些错误。 我的来源几乎是维基百科https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps

/**
 *
 * @return int[]{lower, upper}, i.e. int array with Lower and Upper Boundary of the 95% Confidence Interval for the given numbers
 */
private static double[] calculateLowerUpperConfidenceBoundary95Percent(int[] givenNumbers) {

    // calculate the mean value (= average)
    double sum = 0.0;
    for (int num : givenNumbers) {
        sum += num;
    }
    double mean = sum / givenNumbers.length;

    // calculate standard deviation
    double squaredDifferenceSum = 0.0;
    for (int num : givenNumbers) {
        squaredDifferenceSum += (num - mean) * (num - mean);
    }
    double variance = squaredDifferenceSum / givenNumbers.length;
    double standardDeviation = Math.sqrt(variance);

    // value for 95% confidence interval, source: https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps
    double confidenceLevel = 1.96;
    double temp = confidenceLevel * standardDeviation / Math.sqrt(givenNumbers.length);
    return new double[]{mean - temp, mean + temp};
}

答案 1 :(得分:-3)

这里是你去这是代码计算Confidence Interval

/**
 *
 * @author alaaabuzaghleh
 */
public class TestCI {
    public static void main(String[] args) { 
        int maximumNumber = 100000;
        int num = 0;
        double[] data = new double[maximumNumber];

        // first pass: read in data, compute sample mean
        double dataSum = 0.0;
        while (num<maximumNumber) {
            data[num] = num*10;
            dataSum  += data[num];
            num++;
        }
        double ave = dataSum / num;


        double variance1 = 0.0;
        for (int i = 0; i < num; i++) {
            variance1 += (data[i] - ave) * (data[i] - ave);
        }
        double variance = variance1 / (num - 1);
        double standardDaviation= Math.sqrt(variance);
        double lower = ave - 1.96 * standardDaviation;
        double higher = ave + 1.96 * standardDaviation;

        // print results
        System.out.println("average          = " + ave);
        System.out.println("sample variance  = " + variance);
        System.out.println("sample standard daviation    = " + standardDaviation);
        System.out.println("approximate confidence interval");
        System.out.println("[ " + lower + ", " + higher + " ]");
}
}