簡體   English   中英

代碼中的Java編程標准偏差錯誤

[英]Java programming standard deviation error in code

我的標准差是偏離的。 當我輸入時:2 4 4 4 5 5 7 9 n

我沒有得到2.這是我的代碼。 我相信一切都檢查出來所以我不明白為什么我一直得到1.8284791953425266而不是2:

import java.util.Scanner;

public class stocks {

  public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     double currentNum = 0;
     double numtotal = 0;
     int count = 0;
     double mean = 0;
     double square = 0, squaretotal = 0, sd = 0;

     System.out.println("Enter a series of double value numbers, ");
     System.out.println("Enter anything other than a number to quit: ");

     while (in.hasNextDouble()) 
     {

         currentNum = in.nextDouble();
         numtotal = numtotal + currentNum;

         count++;
         mean = (double) numtotal / count;
         square = Math.pow(currentNum - mean, 2.0);
         squaretotal = squaretotal + square; 
         sd = Math.pow(squaretotal/count, 1/2.0);
     }

     System.out.println("The mean is: " +mean);
     System.out.println("The standard deviation is: " +sd);

     }


 }

在計算標准偏差之前,您需要計算所有數字的均值。 現在你的平均值是所有數字的平均值,直到當前數字。 你的問題在這里

square = Math.pow(currentNum - mean, 2.0);

在這一點上,平均值是我們看到的數字的平均值。 這是因為numtotal是我們看到的數字的總和。 要解決此問題,您可以先將所有數字輸入到數組列表中。 然后計算所有數字的均值,然后你可以計算出方差和標准偏差。

如果你要除以它, count需要是一個雙倍。

mean = (double) numtotal / count;

- >

mean = (double) numtotal / (double) count;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM