A formula for calculating the variance of an entire population of size N is:
Using Bessel's correction to calculate an unbiased estimate of the population variance from a finite sample of n observations, the formula is:
Therefore, a naïve algorithm to calculate the estimated variance is given by the following:
Let n ← 0, Sum ← 0, SumSq ← 0
For each datum x:
n ← n + 1
Sum ← Sum + x
SumSq ← SumSq + x × x
Var = (SumSq − (Sum × Sum) / n) / (n − 1)
This algorithm can easily be adapted to compute the variance of a finite population: simply divide by n instead of n − 1 on the last line.
Because SumSq and (Sum×Sum)/n can be very similar numbers, cancellation can lead to the precision of the result to be much less than the inherent precision of the floating-point arithmetic used to perform the computation. Thus this algorithm should not be used in practice,[1][2] and several alternate, numerically stable, algorithms have been proposed.[3] This is particularly bad if the standard deviation is small relative to the mean.
Computing shifted data
The variance is invariant with respect to changes in a location parameter, a property which can be used to avoid the catastrophic cancellation in this formula.
with any constant, which leads to the new formula
the closer is to the mean value the more accurate the result will be, but just choosing a value inside the
samples range will guarantee the desired stability. If the values are small then there are no problems with the sum of its squares, on the contrary, if they are large it necessarily means that the variance is large as well. In any case the second term in the formula is always smaller than the first one therefore no cancellation may occur.[2]
defshifted_data_variance(data):iflen(data)<2:return0.0K=data[0]n=Ex=Ex2=0.0forxindata:n+=1Ex+=x-KEx2+=(x-K)**2variance=(Ex2-Ex**2/n)/(n-1)# use n instead of (n-1) if want to compute the exact variance of the given data# use (n-1) if data are samples of a larger populationreturnvariance
This formula also facilitates the incremental computation that can be expressed as
This algorithm is numerically stable if n is small.[1][4] However, the results of both of these simple algorithms ("naïve" and "two-pass") can depend inordinately on the ordering of the data and can give poor results for very large data sets due to repeated roundoff error in the accumulation of the sums. Techniques such as compensated summation can be used to combat this error to a degree.
Welford's online algorithm
It is often useful to be able to compute the variance in a single pass, inspecting each value only once; for example, when the data is being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. For such an online algorithm, a recurrence relation is required between quantities from which the required statistics can be calculated in a numerically stable fashion.
The following formulas can be used to update the mean and (estimated) variance of the sequence, for an additional element xn. Here, denotes the sample mean of the first n samples , their biased sample variance, and their unbiased sample variance.
These formulas suffer from numerical instability [citation needed], as they repeatedly subtract a small number from a big number which scales with n. A better quantity for updating is the sum of squares of differences from the current mean, , here denoted :
This algorithm was found by Welford,[5][6] and it has been thoroughly analyzed.[2][7] It is also common to denote and .[8]
An example Python implementation for Welford's algorithm is given below.
# For a new value new_value, compute the new count, new mean, the new M2.# mean accumulates the mean of the entire dataset# M2 aggregates the squared distance from the mean# count aggregates the number of samples seen so fardefupdate(existing_aggregate,new_value):(count,mean,M2)=existing_aggregatecount+=1delta=new_value-meanmean+=delta/countdelta2=new_value-meanM2+=delta*delta2return(count,mean,M2)# Retrieve the mean, variance and sample variance from an aggregatedeffinalize(existing_aggregate):(count,mean,M2)=existing_aggregateifcount<2:returnfloat("nan")else:(mean,variance,sample_variance)=(mean,M2/count,M2/(count-1))return(mean,variance,sample_variance)
This algorithm is much less prone to loss of precision due to catastrophic cancellation, but might not be as efficient because of the division operation inside the loop. For a particularly robust two-pass algorithm for computing the variance, one can first compute and subtract an estimate of the mean, and then use this algorithm on the residuals.
The parallel algorithm below illustrates how to merge multiple sets of statistics calculated online.
Weighted incremental algorithm
The algorithm can be extended to handle unequal sample weights, replacing the simple counter n with the sum of weights seen so far. West (1979)[9] suggests this incremental algorithm:
defweighted_incremental_variance(data_weight_pairs):w_sum=w_sum2=mean=S=0forx,windata_weight_pairs:w_sum=w_sum+ww_sum2=w_sum2+w**2mean_old=meanmean=mean_old+(w/w_sum)*(x-mean_old)S=S+w*(x-mean_old)*(x-mean)population_variance=S/w_sum# Bessel's correction for weighted samples# for integer frequency weightssample_frequency_variance=S/(w_sum-1)
Chan et al.[10] note that Welford's online algorithm detailed above is a special case of an algorithm that works for combining arbitrary sets and :
.
This may be useful when, for example, multiple processing units may be assigned to discrete parts of the input.
Chan's method for estimating the mean is numerically unstable when and both are large, because the numerical error in is not scaled down in the way that it is in the case. In such cases, prefer .
This can be generalized to allow parallelization with AVX, with GPUs, and computer clusters, and to covariance.[3]
Example
Assume that all floating point operations use standard IEEE 754 double-precision arithmetic. Consider the sample (4, 7, 13, 16) from an infinite population. Based on this sample, the estimated population mean is 10, and the unbiased estimate of population variance is 30. Both the naïve algorithm and two-pass algorithm compute these values correctly.
Next consider the sample (108 + 4, 108 + 7, 108 + 13, 108 + 16), which gives rise to the same estimated variance as the first sample. The two-pass algorithm computes this variance estimate correctly, but the naïve algorithm returns 29.333333333333332 instead of 30.
While this loss of precision may be tolerable and viewed as a minor flaw of the naïve algorithm, further increasing the offset makes the error catastrophic. Consider the sample (109 + 4, 109 + 7, 109 + 13, 109 + 16). Again the estimated population variance of 30 is computed correctly by the two-pass algorithm, but the naïve algorithm now computes it as −170.66666666666666. This is a serious problem with naïve algorithm and is due to catastrophic cancellation in the subtraction of two similar numbers at the final stage of the algorithm.
Higher-order statistics
Terriberry[11] extends Chan's formulae to calculating the third and fourth central moments, needed for example when estimating skewness and kurtosis:
Here the are again the sums of powers of differences from the mean , giving
For the incremental case (i.e., ), this simplifies to:
By preserving the value , only one division operation is needed and the higher-order statistics can thus be calculated for little incremental cost.
An example of the online algorithm for kurtosis implemented as described is:
defonline_kurtosis(data):n=mean=M2=M3=M4=0forxindata:n1=nn=n+1delta=x-meandelta_n=delta/ndelta_n2=delta_n**2term1=delta*delta_n*n1mean=mean+delta_nM4=M4+term1*delta_n2*(n**2-3*n+3)+6*delta_n2*M2-4*delta_n*M3M3=M3+term1*delta_n*(n-2)-3*delta_n*M2M2=M2+term1# Note, you may also calculate variance using M2, and skewness using M3# Caution: If all the inputs are the same, M2 will be 0, resulting in a division by 0.kurtosis=(n*M4)/(M2**2)-3returnkurtosis
Pébaÿ[12]
further extends these results to arbitrary-order central moments, for the incremental and the pairwise cases, and subsequently Pébaÿ et al.[13]
for weighted and compound moments. One can also find there similar formulas for covariance.
Choi and Sweetman[14]
offer two alternative methods to compute the skewness and kurtosis, each of which can save substantial computer memory requirements and CPU time in certain applications. The first approach is to compute the statistical moments by separating the data into bins and then computing the moments from the geometry of the resulting histogram, which effectively becomes a one-pass algorithm for higher moments. One benefit is that the statistical moment calculations can be carried out to arbitrary accuracy such that the computations can be tuned to the precision of, e.g., the data storage format or the original measurement hardware. A relative histogram of a random variable can be constructed in the conventional way: the range of potential values is divided into bins and the number of occurrences within each bin are counted and plotted such that the area of each rectangle equals the portion of the sample values within that bin:
where and represent the frequency and the relative frequency at bin and is the total area of the histogram. After this normalization, the raw moments and central moments of can be calculated from the relative histogram:
where the superscript indicates the moments are calculated from the histogram. For constant bin width these two expressions can be simplified using :
The second approach from Choi and Sweetman[14] is an analytical methodology to combine statistical moments from individual segments of a time-history such that the resulting overall moments are those of the complete time-history. This methodology could be used for parallel computation of statistical moments with subsequent combination of those moments, or for combination of statistical moments computed at sequential times.
If sets of statistical moments are known:
for , then each can
be expressed in terms of the equivalent raw moments:
where is generally taken to be the duration of the time-history, or the number of points if is constant.
The benefit of expressing the statistical moments in terms of is that the sets can be combined by addition, and there is no upper limit on the value of .
where the subscript represents the concatenated time-history or combined . These combined values of can then be inversely transformed into raw moments representing the complete concatenated time-history
Known relationships between the raw moments () and the central moments ()
are then used to compute the central moments of the concatenated time-history. Finally, the statistical moments of the concatenated history are computed from the central moments:
Covariance
Very similar algorithms can be used to compute the covariance.
Naïve algorithm
The naïve algorithm is
For the algorithm above, one could use the following Python code:
As for the variance, the covariance of two random variables is also shift-invariant, so given any two constant values and it can be written:
and again choosing a value inside the range of values will stabilize the formula against catastrophic cancellation as well as make it more robust against big sums. Taking the first value of each data set, the algorithm can be written as:
A slightly more accurate compensated version performs the full naive algorithm on the residuals. The final sums and should be zero, but the second pass compensates for any small error.
Online
A stable one-pass algorithm exists, similar to the online algorithm for computing the variance, that computes co-moment :
The apparent asymmetry in that last equation is due to the fact that , so both update terms are equal to . Even greater accuracy can be achieved by first computing the means, then using the stable one-pass algorithm on the residuals.
Thus the covariance can be computed as
defonline_covariance(data1,data2):meanx=meany=C=n=0forx,yinzip(data1,data2):n+=1dx=x-meanxmeanx+=dx/nmeany+=(y-meany)/nC+=dx*(y-meany)population_covar=C/n# Bessel's correction for sample variancesample_covar=C/(n-1)
A small modification can also be made to compute the weighted covariance:
defonline_weighted_covariance(data1,data2,data3):meanx=meany=0wsum=wsum2=0C=0forx,y,winzip(data1,data2,data3):wsum+=wwsum2+=w*wdx=x-meanxmeanx+=(w/wsum)*dxmeany+=(w/wsum)*(y-meany)C+=w*dx*(y-meany)population_covar=C/wsum# Bessel's correction for sample variance# Frequency weightssample_frequency_covar=C/(wsum-1)# Reliability weightssample_reliability_covar=C/(wsum-wsum2/wsum)
Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation:[3]
Weighted batched version
A version of the weighted online algorithm that does batched updated also exists: let denote the weights, and write
^Ling, Robert F. (1974). "Comparison of Several Algorithms for Computing Sample Means and Variances". Journal of the American Statistical Association. 69 (348): 859–866. doi:10.2307/2286154. JSTOR2286154.
^Cook, John D. (30 September 2022) [1 November 2014]. "Accurately computing sample variance". John D. Cook Consulting: Expert consulting in applied mathematics & data privacy.
^ abChoi, Myoungkeun; Sweetman, Bert (2010). "Efficient Calculation of Statistical Moments for Structural Health Monitoring". Journal of Structural Health Monitoring. 9 (1): 13–24. doi:10.1177/1475921709341014. S2CID17534100.
Romain Bussine Romain Bussine (4 November 1830 – 20 Desember 1899) adalah seorang guru vokal, penyanyi, penerjemah dan penyair Prancis. Ia aktif pada paruh kedua abad ke-19. Referensi dan sumber Referensi Sumber Johnson, Graham (2005). Un paysage choisi. London: Hyperion Records. OCLC 60709962. Nectoux, Jean-Michel (1984). Gabriel Fauré: His Life Through Letters. London: Boyars. ISBN 978-0-71-452768-0. Pengawasan otoritas Umum Integrated Authority File (...
Lawrence GonziKUOM Perdana Menteri Malta ke-12Masa jabatan23 Maret 2004 – 11 Maret 2013PresidenGuido de Marco Edward Fenech AdamiGeorge AbelaWakilTonio Borg Simon Busuttil PendahuluEdward Fenech AdamiPenggantiJoseph MuscatKetua Negara Persemakmuran ke-4Masa jabatan25 November 2005 – 23 November 2007Kepala PersemakmuranElizabeth II PendahuluOlusegun ObasanjoPenggantiYoweri Museveni Informasi pribadiLahir01 Juli 1953 (umur 70)Valletta, Malta InggrisPartai politikNatio...
Sunfishes Periode Eosen Awal hingga Sekarang Centrarchidae Flier (Centrarchus macropterus)TaksonomiKerajaanAnimaliaFilumChordataKelasActinopteriOrdoCentrarchiformesUpaordoCentrarchoideiFamiliCentrarchidae Cope GeneraLihat teksDistribusiCentrarchidae native range lbs Centrarchidae atau kakap sungai adalah keluarga ikan bersirip air tawar yang termasuk ordo Perciformes [1](sebelumnya milik Centrarchiformes yang sudah tidak digunakan lagi). Jenis genus adalah Centrarchus (hanya terdiri d...
Ordre de la Double Croix Blanche(sk) Rad Bieleho dvojkríža Avers Insigne et croix de l’ordre. Conditions Décerné par Slovaquie Type Ordre honorifique civil et militaire Éligibilité Militaires ou civils tchèques ou étrangers Détails Statut Toujours décerné Grades Du plus haut au plus bas : Ire classeIIe classeIIIe classe Statistiques Création 1er mars 1994 Ordre de préséance Inférieur Équivalent SupérieurAucun modifier L'ordre de la Double Croix Blanche (en slova...
1939 film by William A. Wellman Beau GesteOriginal theatrical posterDirected byWilliam A. WellmanScreenplay byRobert CarsonBased onBeau Gesteby P. C. WrenProduced byWilliam A. WellmanStarringGary Cooper Ray Milland Robert Preston Brian Donlevy Susan HaywardCinematographyTheodor Sparkuhl Archie StoutEdited byThomas ScottMusic byAlfred NewmanColor processBlack and whiteProductioncompanyParamount PicturesDistributed byParamount PicturesRelease date July 24, 1939 (1939-07-24) Runni...
Salicaceae Salix caprea Klasifikasi ilmiah Kerajaan: Plantae Divisi: Angiospermae (tanpa takson): Eudikotil (tanpa takson): Rosidae Ordo: Malphigiales Famili: SalicaceaeMirb. Genera Lihat artikel. Suku dedalu-dedaluan atau Salicaceae adalah salah satu suku anggota tumbuhan berbunga. Menurut Sistem klasifikasi APG II suku ini dimasukkan ke dalam bangsa Malpighiales, klad euRosidae I. Dedalu adalah pohon atau perdu peluruh yang daunnya sederhana, bunganya tunggal, dan tak berdaun mahkota. Keba...
Pour les articles homonymes, voir La Rochefoucauld. Edmée de La RochefoucauldPortrait d'Edmée de La Rochefoucauld.FonctionPrésidenteUnion nationale pour le vote des femmes (d)BiographieNaissance 28 avril 189517e arrondissement de ParisDécès 20 septembre 1991 (à 96 ans)16e arrondissement de ParisSépulture MontmirailNom de naissance Edmée Christiane Marie Frisch de FelsNationalité françaiseDomicile Hôtel de La Rochefoucauld (d)Activités Écrivaine, biographePère Edm...
American farmer (1919–1973) Max YasgurYasgur at Woodstock in 1969, which was held on part of his dairy farm in Bethel, New YorkBornMax B. Yasgur(1919-12-15)December 15, 1919New York City, U.S.DiedFebruary 9, 1973(1973-02-09) (aged 53)Marathon, Florida, U.S.Alma materNew York UniversityOccupationFarmerYears active1949−1971Known forLeasing a field of his farm for the purpose of holding the Woodstock festivalPolitical partyRepublicanChildrenSam, Lois Yasgur's farm at 27 Y...
Celtic FrostLa band in un concerto del 2006 Paese d'origine Svizzera GenereThrash metal[1][2]Black metal[1][2]Avant-garde metal[3]Hair metal[1]Power metal[4]Speed metalHeavy metal Periodo di attività musicale1984 – 19932001 – 2008 EtichettaCentury Media Album pubblicati8 Studio6 Raccolte2 Opere audiovisive1 Modifica dati su Wikidata · Manuale I Celtic Frost (pronuncia: [ 'keltɪk fɹɒst ]) so...
English television and radio presenter For her radio show, see Fearne Cotton (radio show). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Fearne Cotton – news · newspapers · books · scholar · JSTOR (April 2024) (Learn how and when to remove this message) Fearne CottonCotton in 2014Born (1981-09-03) 3 Septem...
Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Politeknik Kesehatan Kementerian Kesehatan Banten – berita · surat kabar · buku · cendekiawan · JSTOR Politeknik Kesehatan BantenJenisPerguruan Tinggi Kedinasan, di bawah Kementerian Kesehatan Republik I...
Pro Wrestling IllustratedSampul Penghargaan Akhir Tahun PWI 2014 menampilkan Daniel BryanKategoriOlahragaFrekuensiBulananPenerbitKappa Publishing GroupTerbitan pertamaSeptember 1979NegaraAmerika SerikatBahasaBahasa InggrisSitus webwww.pwi-online.comISSN1043-7576Pro Wrestling Illustrated (PWI) adalah majalah gulat profesional Amerika Serikat yang dijual secara internasional yang didirikan pada tahun 1979 oleh penerbit Stanley Weston.[1] PWI berkantor pusat di Blue Bell, Pennsylvania, d...
Television studios in Manhattan, New York This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: CBS Broadcast Center – news · newspapers · books · scholar · JSTOR (July 2009) (Learn how and when to remove this message) CBS Broadcast CenterThe broadcast center at 524 West 57th Street.General informationTypeTelevisi...
American electronic music DJ and remixer For the poet and humorist, see Wilbur D. Nesbit. Josh WinkJosh Wink performing live (13 May 2007)Background informationBirth nameJoshua WinkelmanAlso known asAccent, The Crusher, Dinky Dog, Size 9, Wink, WinxBorn (1970-04-20) April 20, 1970 (age 54)Philadelphia, United StatesGenres Big beat electronic acid house drum and bass breakbeat Occupation(s)DJ, producer, label ownerYears active1990–presentLabelsOvum RecordingsWebsiteJosh Wink.com & E...
V.LeagueBadan yang mengaturVPFNegaraVietnamKonfederasiAFCDibentuk1980; 44 tahun lalu (1980) (Semi-professional)2000; 24 tahun lalu (2000) (Professional)Musim perdana1980 (sebagai Piala Nasional Vietnam A1)Jumlah tim14Tingkat pada piramida1Degradasi ke V.League 2Piala domestikPiala Nasional VietnamPiala Super VietnamPiala internasionalLiga Champions AFCPiala AFCKejuaraan Klub ASEANJuara bertahan ligaHà Nội (5 Gelar) (2019)Klub tersuksesHà Nội Thể Công (5 gelar)Pencetak gol t...
Planned metro system in Baotou, China You can help expand this article with text translated from the corresponding article in Chinese. (January 2023) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Do not transl...
Disambiguazione – Se stai cercando altri significati, vedi Campionato mondiale costruttori. Il campionato mondiale costruttori di Formula 1 (in inglese Formula One World Constructors' Championship, abbreviato WCC) viene attribuito ufficialmente dalla Federazione Internazionale dell'Automobile ed è determinato da un particolare sistema di punteggio, che nel corso degli anni è variato, basato sui risultati ottenuti in ogni Gran Premio. Indice 1 Criterio 2 Statistiche 3 Albo d'oro 3.1 Per s...
Toyota AquaToyota Prius c Marque Toyota Années de production Depuis 2011 Classe Petite Moteur et transmission Moteur(s) 4 cylindres essence + bloc électrique Cylindrée 1 496 cm3 Puissance maximale Thermique : 74 ch + électrique : 61 ch Transmission Traction Boîte de vitesses CVT sans vitesse Masse et performances Masse à vide 1 050 à 1 080 kg Châssis - Carrosserie Carrosserie(s) 5 portes, 5 places Dimensions Longueur 3 995 mm Largeur ...