简体   繁体   English

计算Java中的平均数

[英]Calculate average number in Java

Below is example of time series data: 以下是时间序列数据的示例:

time - 3 sec, value  - 6 
time - 10 sec, value - 7
time - 12 sec, value - 8
time - 17 sec, value - 9
time - 28 sec, value - 93
time - 29 sec, value - 94

I would like to calculate the average value for the last 30 seconds. 我想计算最近30秒的平均值。 Is there any simple standard algorithm for that ? 是否有任何简单的标准算法? Would be nice to see a link to Java implementation as well 也很高兴看到与Java实现的链接

I wrote(with a friend) a code that calculates the average number: 我(和一个朋友)写了一个计算平均值的代码:

package dingen;
import java.util.Scanner;


public class Gemiddelde {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);

    float maxCount = 0;
    float avgCount = 0;

    System.out.println("How many numbers do you want");

    int n = sc.nextInt();

    for(int i = 0; i < n; i++) {
        System.out.println("Number: ");
        float number = sc.nextInt();
        maxCount = maxCount + number;

    }

    avgCount = maxCount / n;
    System.out.println("maxCount = " + maxCount);
    System.out.println("avgCount = " + avgCount);
}

}

the only thing you have to do is replace your class and package. 唯一要做的就是替换您的类和包。

you will get the message: How many numbers do you want?: 您将收到消息: How many numbers do you want?:

and then it wil ask you the amount of numbers you inserted. 然后它会问您插入的号码数量。

example: 例:

How many numbers do you want?:6 您要多少个号码?:6

Number:6 数量:6

Number:7 数量:7

Number:8 数量:8

Number:9 编号:9

Number:93 数量:93

Number:94 数:94

maxCount = 217.0 maxCount = 217.0

avgCount = 36.166668 avgCount = 36.166668

I have hoped I helped you with your problem :) 我希望我能帮助您解决您的问题:)

I'd use a TreeMap<Integer, Integer> , with the key being the seconds and the value, well, your value ;) 我会使用TreeMap<Integer, Integer> ,键是秒,值是你的值;)

TreeMap has useful methods, such as lastKey() and tailMap() , which would fit your use case: TreeMap具有有用的方法,例如lastKey()tailMap() ,它们适合您的用例:

TreeMap<Integer, Integer> map = new TreeMap<>();

// add all your entries

Integer lastSecond = map.lastKey(); // returns the highest key

Integer thirtySecondsAgo = lastSecond - 30;

SortedMap<Integer, Integer> range = map.tailMap(thirtySecondsAgo);

int count = 0;
int sum = 0;
for (Integer value : range.values()) {
    sum += value;
    count++;
}

double average = (double) sum / (double) count;

tailMap() docs: tailMap()文件:

Returns a view of the portion of this map whose keys are greater than or equal to fromKey 返回此地图的一部分的视图,其键大于或等于fromKey

For your problem, fromKey would be thirtySecondsAgo . 对于您的问题, fromKey将为thirtySecondsAgo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM