[英]Average Random Integers
我正在嘗試編寫一個程序,該程序以整數作為命令行參數,使用random打印0到1之間的N
均勻隨機值,然后打印其平均值。
我不確定在while循環中要放入什么參數,以便隨機整數重復n
次, n
是用戶的數字,表示隨機數必須生成的整數。
任何幫助,將不勝感激。
如果您只需要執行特定次數的循環,則可以使用for
循環
以下循環將精確地迭代n
次,這就是我個人需要精確地進行n
次操作時使用的方式。
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
在您的PRNG行為正確的前提下,您只需要這樣做:
main()
{
printf("\n0.5");
exit(0);
}
這對於N足夠大...以恆定時間計算。 否則使用移動平均公式:
http://en.wikipedia.org/wiki/Moving_average
它只需要O(1)的存儲空間,而不需要朴素的O(N)方法
這是剪切並粘貼的Java代碼:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.