Variance Calculator
Free online variance calculator for sample and population variance. Paste comma-separated numbers or upload a CSV, compare groups side by side, and get the standard deviation, coefficient of variation, a confidence interval for the variance, equal-variance tests and every step of the working.
⚡ 0. Quick Answer
A variance calculator measures spread as the average squared distance from the mean. Subtract the mean from each value, square the differences, add them, then divide by n − 1 for a sample or n for a population. For 16 leaf lengths (52, 48, 55, 61, 47, ...), the sample variance is 17.60 mm² and the SD is 4.19 mm.
Rule of thumb: use the sample variance (n − 1) when your data are a sample from a larger group, which is almost always. Use the population variance (n) only when you measured every member. Take the square root of the variance to get the standard deviation in the original units.
🔑 Key Takeaways
- A variance calculator measures spread as the mean of squared deviations; for the worked leaf data it gives s² = 17.5958.
- Sample variance divides by n − 1 (Excel VAR.S, R var()), while population variance divides by n (Excel VAR.P), giving 16.4961 for the same data.
- Variance is in squared units, so the standard deviation, √17.5958 = 4.1947, is the number to describe your data in words.
- The 95% confidence interval for this variance runs from 9.60 to 42.15, which shows how uncertain a variance from 16 values still is.
- To compare variances between groups, use Levene's test (robust) or Bartlett's test (needs normal data); this calculator runs both automatically.
📚 1. What Is Variance?
Variance is a number that tells you how spread out your data are. It is the average of the squared distances between each value and the mean. If all values are the same, the variance is zero. The more the values scatter away from the mean, the larger the variance becomes.
Why square the distances? Some values sit above the mean and some below, so the plain distances always add up to zero. Squaring makes every distance positive, and it gives big distances more weight than small ones. The price is that the answer is in squared units: if you measure in millimetres, the variance is in mm². That is why we usually also report the standard deviation, which is the square root of the variance and is back in the original units.
What this calculator reports for each group:
- Sample variance (s²), dividing by n − 1. Use it for samples.
- Population variance (σ²), dividing by n. Use it only when you have every member of the group.
- Sample and population standard deviation, the square roots of the two variances.
- Sum of squares (SS), the top line of both variance formulas.
- Coefficient of variation (CV), the SD as a percentage of the mean.
- Standard error of the mean, range, IQR and MAD for context.
- Confidence interval for the variance and SD, from the chi-square distribution.
- Equal-variance tests across groups: Levene's (Brown-Forsythe), Bartlett's and, for two groups, the F-test.
A worked one-liner: for the values 2, 4, 4, 4, 5, 5, 7 and 9, the mean is 5. The squared deviations are 9, 1, 1, 1, 0, 0, 4 and 16, which add up to 32. Divide by n = 8 and the population variance is 4 (SD = 2). Divide by n − 1 = 7 and the sample variance is 4.5714 (SD = 2.1381).
Who uses variance: scientists use it to describe how consistent their measurements are. Quality engineers use it to check whether a machine fills bottles precisely. Investors use the variance of returns as a measure of risk. Ecologists compare variance between sites to see which habitat is more uniform. It is also the building block of the t-test, ANOVA (analysis of variance), regression and almost every other statistical test.
| Measure | What it shows | Units | Use it when |
|---|---|---|---|
| Variance | Average squared distance from the mean | Squared (mm²) | Doing calculations, tests and models; adding up independent sources of spread |
| Standard deviation | Typical distance from the mean | Original (mm) | Describing spread in words, tables and error bars |
| Coefficient of variation | SD as a percent of the mean | None (%) | Comparing spread between groups with different means or units |
| Range | Largest minus smallest | Original | A quick, rough view; very sensitive to outliers |
| IQR | Spread of the middle 50% | Original | Skewed data or data with outliers |
🧮 2. Set Up Your Data
Type one value per cell. Each column becomes a group, and you can rename the column headers. Empty cells are ignored, so groups can have different sizes.
Quick variance converters
Small tools for the most common side questions. Each one runs only when you press its button.
Standard deviation ↔ variance
Percent variance (budget vs actual)
Variance of a probability distribution
📊 3. Results
🧠 4. Interpretation of Results, In Detail
4.1 What the variance number actually tells you
The variance is the average squared distance from the mean. On its own the number is hard to picture, because it is in squared units. A variance of 17.6 mm² does not mean values sit 17.6 mm from the mean. Take the square root first: an SD of 4.19 mm means a typical value sits about 4 mm away from the mean. Always read the variance and the SD together. Use the variance for calculations and the SD for describing your data in words.
A variance of zero means every value is identical. There is no upper limit. A larger variance always means more spread, but only when you compare data measured on the same scale and in the same units.
4.2 Sample variance or population variance: which number do you report?
The two numbers differ only in the last step. The sample variance divides the sum of squares by n − 1. The population variance divides by n. Dividing by n − 1 is called Bessel's correction. It makes the sample variance an unbiased estimate of the true population variance. Without it, a sample would underestimate the spread on average, because the sample mean is always as close as possible to its own data.
Report the sample variance whenever your data are a sample and you want to say something about a bigger group, which is nearly every research study. Report the population variance only when you have measured every single member of the group you care about, such as all 30 students in one class when you only want to describe that class. The gap between the two shrinks as n grows: at n = 16 it is about 6%, at n = 100 it is 1%.
4.3 Turning the variance into a standard deviation and a CV
The standard deviation is the square root of the variance, so it is back in your original units. For roughly bell-shaped data, about 68% of values fall within one SD of the mean and about 95% within two SDs. That rule helps you picture the spread quickly.
The coefficient of variation (CV) is the SD divided by the mean, times 100. It has no units, so you can compare the spread of groups with very different means. As a rough guide for lab and field data, a CV under 10% is low, 10% to 30% is moderate, and over 30% is high. The CV only makes sense for data on a ratio scale with a true zero and a positive mean. Do not use it for temperatures in Celsius or for data with negative values (Reed et al., 2002).
4.4 How precise is your variance? Reading the confidence interval
A variance from a sample is only an estimate. The confidence interval shows the range of true population variances that fit your data. It comes from the chi-square distribution and is not symmetric: the upper limit is always further from the estimate than the lower limit. With small samples the interval is very wide. For n = 16, the 95% interval for the leaf data runs from 9.60 to 42.15, more than four times wider at the top than at the bottom.
This interval assumes the data come from a normal distribution, and it is sensitive to that assumption. If your data are skewed or have heavy tails, treat the interval as approximate, or use a bootstrap interval in R or Python.
4.5 Comparing variances between groups
When you enter two or more groups, the calculator tests whether their variances differ. Three tests are shown, and they answer the same question in different ways:
- Levene's test, median-centred (Brown-Forsythe). The robust choice. It works well even when the data are not normal. This is the default in R's
car::leveneTestand SciPy'slevene(Brown & Forsythe, 1974). - Bartlett's test. More powerful when the data really are normal, but it gives false alarms when they are not (Box, 1953). Trust it only after checking normality.
- F-test (two groups only). The ratio of the two sample variances. It is the classic textbook test and what Excel's
F.TESTreturns, but it is very sensitive to non-normal data.
A p-value below your significance level means the variances are unlikely to be equal. A p-value above it means you have no strong evidence that they differ. It does not prove they are equal, especially with small groups.
4.6 What a large or small variance means in practice
Whether a variance is "large" depends entirely on the subject. In manufacturing, a fill-volume variance of 1.7 ml² may fail a quality standard. In exam scores, a variance of 68 points² may be completely normal. Judge your number against three things: the measurement precision of your instrument, published values for similar data, and the practical tolerance in your field. The CV helps here because it puts spread on a common percentage scale.
A small variance means your values are consistent. That is good news for a machine or a lab assay. It can be bad news for a study that needs variety, such as a sample meant to cover a wide range of ages.
4.7 Why one outlier can dominate the variance
Because distances are squared, a value that sits 10 units from the mean adds 100 to the sum of squares, while a value 1 unit away adds only 1. A single outlier can therefore make up most of the variance. In the skewed income sample on this page, one high earner contributes 91% of the total sum of squares. The calculator's checks table shows the largest single share, so you can see when this happens.
When one value dominates, check it first. If it is a data entry error, fix it. If it is real, report the variance with and without it, or report robust measures such as the IQR or the median absolute deviation (MAD) alongside (Leys et al., 2013).
4.8 Unequal variances and what to do next
Many tests, including the Student t-test and classic one-way ANOVA, assume that groups have equal variances. If Levene's test is significant, or if the largest variance is more than about four times the smallest, switch to a method that does not need equal variances:
- For two group means, use Welch's t-test instead of Student's t-test.
- For three or more group means, use Welch's ANOVA with Games-Howell post-hoc tests.
- In regression, use robust (heteroscedasticity-consistent) standard errors or model the variance directly.
Sometimes the difference in variance is the finding itself. A new teaching method that makes scores more consistent, or a treatment that stabilises blood pressure, is a real result worth reporting.
4.9 The ratio of largest to smallest variance
The calculator reports the variance ratio, also called Hartley's F-max. It is a quick rule of thumb. A ratio under 2 suggests the variances are similar. Between 2 and 4 is a grey zone. Above 4, most methods that assume equal variances become unreliable, especially when the group sizes are also unequal. Use it alongside the formal tests, not instead of them (Hartley, 1950).
4.10 Variance, standard error and sample size are different things
The variance describes how spread out individual values are. It does not shrink as you collect more data; it settles towards the true population value. The standard error of the mean, s ÷ √n, describes how precisely you know the mean, and it does shrink as n grows. Mixing these up is one of the most common errors in published papers (Altman & Bland, 2005). Use the SD or variance to describe your data, and the SE or a confidence interval to describe the precision of a mean.
4.11 Common mistakes this calculator prevents
- Using the wrong denominator. Both the n − 1 and n versions are shown, labelled with their Excel functions.
- Reporting variance in the wrong units. Units are shown squared for the variance and plain for the SD.
- Forgetting that NumPy defaults to the population variance. Sections 9.4 and 11 show the fix.
- Treating blanks as zeros. Blank cells are skipped, and non-numeric entries are listed so you can fix them.
- Missing a dominant outlier. The checks table flags any value that contributes over half of the sum of squares.
- Trusting Bartlett's test on skewed data. The calculator states when normality looks doubtful and points you to Levene's test.
4.12 A short decision guide
| Your situation | What to report |
|---|---|
| One sample, roughly symmetric data | Sample variance or SD, with n and the mean; add the confidence interval if precision matters |
| You measured the whole population | Population variance and SD |
| Groups with different means or units | CV for each group |
| Two or more groups, normal data | Variances plus Bartlett's or Levene's test |
| Two or more groups, skewed data | Variances plus Levene's (Brown-Forsythe) test, and the IQR |
| One value dominates the sum of squares | Variance with and without that value, plus the MAD or IQR |
✍ 5. How to Write Your Results in Research
When reporting variance calculator results in APA format, give the variance or SD together with the mean and the sample size, state whether you used the sample (n − 1) or population (n) formula, and name the test if you compared groups. The five templates below fill in automatically after you run the calculator.
▶ Run the analysis above to auto-fill all five examples with your results.
📌 Key conventions for this style
- Use italic s² for a sample variance and σ² only for a true population value.
- Give the variance in squared units, or report the SD in the original units.
- Report test statistics with degrees of freedom, for example F(1, 22) = 5.59, p = .027.
- Write p-values without a leading zero and give exact values unless p < .001.
📌 Key conventions for this style
- Justify why you used the sample or population formula.
- Explain which equal-variance test you used and why, and how its result changed your later analysis.
- Report how outliers were found and whether they were kept.
- Name the software and version used to check the numbers.
📌 Key conventions for this style
- Use the SD, not the variance, because readers understand normal units.
- Avoid symbols such as s², σ or p.
- Say "more consistent" or "more varied" rather than "lower variance".
- Give units every time a number appears.
📌 Key conventions for this style
- Declare the formula once in Methods and keep every number consistent.
- Use one line per group with the same decimal places.
- Put the test result in brackets after the comparison.
- On a poster, show Chart 1 or Chart 3 next to the numbers.
📌 Key conventions for this style
- State the formula, the test and alpha before collecting data.
- Say in advance what you will do if variances are unequal, such as switching to Welch's test.
- Report the observed values so a replication can plan its sample size.
- Share the raw data or the summary statistics: n, mean and variance per group.
∑ 6. Formulas Used
These are the formulas this variance calculator uses, in the order they are computed.
🔀 7. Variance Calculation Flowchart, Step by Step
This flowchart shows how the variance is calculated, step by step, from a raw list of numbers to a checked, reportable result. Every box uses the same worked example as the Excel, R and Python sections: 16 leaf lengths in mm from a botany practical.
Check any box yourself: the Excel sheet in Section 9, the R script in Section 10 and the Python script in Section 11 all return a sample variance of 17.5958 and a population variance of 16.4961 for this dataset.
📝 8. How to Use This Variance Calculator
- Enter your data. Type or paste numbers separated by commas, exactly like the placeholder: 52, 48, 55, 61, 47, ... Spaces, tabs, semicolons and new lines also work, so a column copied from Excel is fine.
- Name each group. The group name box above each data box is editable. A name such as Site A flows into the results table, the charts and the report text.
- Add more groups to compare. Press Add group to compare the variance of two or more groups. Each group has its own Clear and Remove buttons.
- Or upload a file. On the Upload tab, choose a CSV or Excel file, then click the columns you want. Every column you click becomes its own group, named after its header.
- Or use the manual table. Type values into the grid, rename the column headers, and press Use this table.
- Try a sample dataset. Ten built-in datasets cover lab data, quality control, finance, ecology and a skewed set with an outlier.
- Choose your settings. Pick sample (n − 1) or population (n) as the main variance, the confidence level for the interval, the significance level for the equal-variance tests, and your units.
- Press Calculate Variance. Nothing is computed until you do. Changing any data or setting clears old results, so you never read stale numbers.
- Read the results. Check the variance and SD cards, the formula block with your numbers, the step-by-step table, and the equal-variance tests if you have two or more groups.
- Check the charts and export. Use the four charts to see the spread, copy one of the five reporting templates in Section 5, and download a text report or a PDF.
Need only a quick conversion? The converters under the Calculate button turn an SD into a variance, work out a percent variance between a budget and an actual value, and find the variance of a probability distribution.
📈 9. How to Calculate Variance in Excel
Excel has built-in functions for both kinds of variance, so the calculation itself takes one formula. What trips people up is choosing between the four variance functions, getting a confidence interval, comparing two groups, and the business meaning of "variance" in budgets. This section covers all of it, with the spreadsheet shown at each stage, using the same 16 leaf lengths as the rest of the page.
=VAR.S(A2:A17) for the sample variance or =VAR.P(A2:A17) for the population variance, and press Enter.9.1 The functions you need
| You want | Excel function | Note |
|---|---|---|
| Sample variance (n − 1) | =VAR.S(A2:A17) | The usual choice. Same as the older VAR |
| Population variance (n) | =VAR.P(A2:A17) | Same as the older VARP |
| Sample SD | =STDEV.S(A2:A17) | Square root of VAR.S |
| Population SD | =STDEV.P(A2:A17) | Square root of VAR.P |
| Sum of squares | =DEVSQ(A2:A17) | The SS on top of both formulas |
| Variance from an SD | =B2^2 | Square the SD in B2 |
| SD from a variance | =SQRT(B2) | Square root of the variance in B2 |
| Chi-square critical value | =CHISQ.INV(0.975,15) | Left-tail probability, df = n − 1 |
| Two-group F-test p-value | =F.TEST(A2:A13,B2:B13) | Returns a two-tailed p-value |
| Variance including text and TRUE | =VARA(A2:A17) | Counts text as 0 and TRUE as 1; rarely what you want |
VAR and VAR.S give the same answer, and so do VARP and VAR.P. The old names still work for compatibility, but the new ones say clearly which version you used. Write VAR.S or VAR.P in your methods, never just "variance".9.2 Step by step
1 Put your numbers in one column
Type or paste the values down column A with a label in A1. Excel's variance functions skip the text header and any blank cells automatically.
The 16 leaf lengths sit in A2:A17. Only the first eight rows are shown.
2 Calculate the sample and population variance
=VAR.S(A2:A17)=VAR.P(A2:A17)=STDEV.S(A2:A17)=COUNT(A2:A17)Put labels in column B and the formulas in column C so the summary is easy to read.
Sample variance 17.5958 in C2, population variance 16.4961 in C3, sample SD 4.1947 in C4, and n = 16 in C6.
3 Show the working: deviations and squares
Teachers often ask to see the steps. Put the deviation in column B and its square in column C, then fill both down to row 17.
=A2-AVERAGE($A$2:$A$17)=B2^2=SUM(C2:C17)/(COUNT(A2:A17)-1)The dollar signs lock the mean range so it does not move when you fill down. Column B adds up to 0; column C adds up to the sum of squares, 263.9375. The last formula divides by n − 1 and returns the same 17.5958 as VAR.S.
For 52 mm the deviation is −0.4375 and its square is 0.1914 (C2). For 61 mm the square is 73.3164, the largest single share.
4 Add a confidence interval for the variance
Excel has no single function for this, but two short formulas do it. C2 holds n and C3 holds the sum of squares from DEVSQ.
=DEVSQ(A2:A17)=C3/CHISQ.INV(0.975,C2-1)=C3/CHISQ.INV(0.025,C2-1)=SQRT(C5)The 95% CI for the variance runs from 9.6018 (C5) to 42.1481 (C6). Square roots give the SD interval, 3.0987 to 6.4922.
5 Compare the variance of two groups
Put each group in its own column. F.TEST returns the two-tailed p-value for equal variances directly.
=VAR.S(A2:A13)=VAR.S(A2:A13)/VAR.S(B2:B13)=F.TEST(A2:A13,B2:B13)Placebo variance 34.3864 (C2), treatment 8.1515 (C3), ratio 4.2184 (C4) and F-test p = 0.0248 (C5), so the variances differ at the 0.05 level.
6 Percent variance for budgets and forecasts
In accounting, "variance" means the difference between a plan and what happened. Format column C as a percentage.
=B2-A2=(B2-A2)/ABS(A2)A budget of 1200 against an actual 1350 is a 12.50% variance (C2). An actual of 720 against 800 is −10.00%.
9.3 The awkward cases
Variance from a standard deviation. If a paper gives only the SD, square it: an SD of 4.1947 gives a variance of 17.5958. If it gives a population SD and you need the sample variance, use =B2^2*n/(n-1).
Variance of grouped or frequency data. With values in A and their counts in B, the sample variance is =SUMPRODUCT(B2:B10,(A2:A10-SUMPRODUCT(A2:A10,B2:B10)/SUM(B2:B10))^2)/(SUM(B2:B10)-1).
Variance of a probability distribution. With values in A and probabilities in B, the mean is =SUMPRODUCT(A2:A5,B2:B5) and the variance is =SUMPRODUCT(B2:B5,(A2:A5-D2)^2), where D2 holds the mean. No n − 1 correction is used here.
Variance by group with a condition. Excel has no VARIF. Use =VAR.S(IF(B2:B50="Site A",A2:A50)), which works directly in Excel 365 and as an array formula (Ctrl + Shift + Enter) in older versions.
F.TEST reports a two-tailed one.9.4 Why your Excel answer might differ from R, Python or a calculator
| Situation | What happens | Fix |
|---|---|---|
NumPy np.var(x) | Defaults to the population variance (ddof = 0), so it matches VAR.P, not VAR.S | Use np.var(x, ddof=1) |
Pandas df["x"].var() | Defaults to the sample variance (ddof = 1), unlike NumPy | No fix needed; it matches VAR.S |
R var(x) | Always the sample variance; R has no population option | Multiply by (n − 1) / n for the population value |
| TI-84 1-Var Stats | Shows Sx and σx (SDs), not the variance | Square Sx for the sample variance, σx for the population variance |
Excel ToolPak F-test vs F.TEST | One-tailed vs two-tailed p-value | Double the ToolPak p, or use F.TEST |
| Blank vs zero cells | Blanks are skipped, zeros are counted and add a big squared deviation | Check COUNT before trusting the variance |
| Levene's test differs between packages | SPSS uses the mean-centred version; R car and SciPy use the median by default | State which centre you used; this page uses the median (Brown-Forsythe) |
| Tool | Sample variance | Population variance | Equal-variance test |
|---|---|---|---|
| Excel | =VAR.S(rng) | =VAR.P(rng) | =F.TEST(r1,r2) |
| Google Sheets | =VAR.S(rng) | =VAR.P(rng) | =F.TEST(r1,r2) |
| R | var(x) | var(x)*(n-1)/n | var.test(), bartlett.test() |
| Python NumPy | np.var(x, ddof=1) | np.var(x) | scipy.stats.levene() |
| Python statistics | statistics.variance(x) | statistics.pvariance(x) | Not available |
| SPSS | Analyze → Descriptive Statistics → Descriptives → Options → Variance; Levene's test appears in Explore and One-Way ANOVA | ||
9.5 Charting variance in Excel
- Put group names in one column and each group's
VAR.Sin the next. - Select both columns, then Insert → Charts → Clustered Column.
- For the more common SD error bars on a mean chart, chart the means instead, click the chart, press +, tick Error Bars, then More Options → Custom → Specify Value and select the
STDEV.Scells. - Say in the caption whether the bars show the SD, the SE or a confidence interval.
- To show raw spread, make a scatter chart with the group number on the x-axis and the values on the y-axis. Chart 1 on this page does this automatically.
9.6 Excel errors you will probably hit
| Excel shows | Why | Fix |
|---|---|---|
#DIV/0! | Fewer than two numbers in the range for VAR.S | Check the range and that numbers are not stored as text |
#NUM! from CHISQ.INV | Probability outside 0 to 1, or df below 1 | Use 0.975 and 0.025 with df = n − 1 |
#VALUE! | Text or a unit symbol typed into a cell | Move units into the header, keep cells numeric |
| Variance is far too big | A zero or a typo such as 520 instead of 52 | Sort the column and look at both ends |
| Variance is 0 | All values identical, or a single value | Check the range covers all your data |
| Green triangles in cells | Numbers stored as text and skipped | Select the cells, click the warning icon, Convert to Number |
| Different from a colleague | One used VAR.S, the other VAR.P | Compare the two: VAR.P = VAR.S × (n − 1) / n |
📈 10. How to Calculate Variance in R
R gives you the sample variance in one word, var(x). The script below is complete and copy-and-run. It shows every step of the calculation, gives both the sample and population variance, builds the confidence interval, prints a plain-English check, and saves one 300 dpi figure. It uses base R only, so there is nothing to install. The commented block at the end compares two groups with the F-test, Bartlett's test and Levene's test.
Rscript. Change only the x <- c(...) line to use your own data.10.1 The complete script
R, base only, saves variance_plot.png
# ============================================================
# Variance calculator: sample and population variance, SD,
# 95% CI for the variance, and one publication-ready figure
# StatsUnlock - https://statsunlock.com/variance-calculator/
# Base R only. No packages to install.
# ============================================================
# ---- 1. Your data ------------------------------------------
# Replace with your own values, or read a CSV:
# x <- read.csv("data.csv")$column_name
x <- c(52, 48, 55, 61, 47, 50, 58, 53,
49, 56, 51, 54, 46, 57, 50, 52)
x <- x[!is.na(x)] # drop missing values
label <- "Leaf length"
units <- "mm"
conf <- 0.95
# ---- 2. Variance, step by step -----------------------------
n <- length(x)
mean_x <- mean(x)
dev <- x - mean_x # deviations, they sum to 0
sq <- dev^2 # squared deviations
ss <- sum(sq) # sum of squares
var_s <- var(x) # sample variance, n - 1 (Excel VAR.S)
var_p <- var_s * (n - 1) / n # population variance, n (Excel VAR.P)
sd_s <- sqrt(var_s)
sd_p <- sqrt(var_p)
cv <- sd_s / mean_x * 100
# ---- 3. Confidence interval for the variance ---------------
a <- 1 - conf
chi_lo <- qchisq(a / 2, df = n - 1)
chi_hi <- qchisq(1 - a / 2, df = n - 1)
ci <- c(ss / chi_hi, ss / chi_lo)
cat(sprintf("n = %d\n", n))
cat(sprintf("mean = %.4f\n", mean_x))
cat(sprintf("sum of squares = %.4f\n", ss))
cat(sprintf("sample variance = %.4f (n - 1)\n", var_s))
cat(sprintf("population variance = %.4f (n)\n", var_p))
cat(sprintf("sample SD = %.4f population SD = %.4f\n", sd_s, sd_p))
cat(sprintf("CV = %.2f%%\n", cv))
cat(sprintf("%.0f%% CI for variance = %.4f to %.4f\n", conf * 100, ci[1], ci[2]))
cat(sprintf("%.0f%% CI for SD = %.4f to %.4f\n", conf * 100, sqrt(ci[1]), sqrt(ci[2])))
share <- max(sq) / ss * 100
cat(sprintf("largest share of SS = %.1f%% -> %s\n", share,
if (share > 50) "one value dominates, check it" else "no single value dominates the variance"))
# ---- 4. One figure, two panels -----------------------------
png("variance_plot.png", width = 3000, height = 1350, res = 300)
par(mfrow = c(1, 2), mar = c(5.5, 4.6, 3.2, 1), family = "sans")
obs <- seq_len(n)
# Left: each value, the mean, and its deviation
plot(obs, x, type = "n", las = 1, xlab = "Observation",
ylab = sprintf("%s (%s)", label, units))
rect(par("usr")[1], mean_x - sd_s, par("usr")[2], mean_x + sd_s,
col = adjustcolor("#16a34a", alpha.f = 0.10), border = NA)
segments(obs, mean_x, obs, x, col = "#9333ea", lwd = 1.6)
points(obs, x, pch = 19, col = "#2563eb", cex = 1.1)
abline(h = mean_x, col = "#c2410c", lwd = 2.2, lty = 2)
title(main = "Deviations from the mean", adj = 0, cex.main = 1)
# Right: squared deviations with the variance line
barplot(sq, names.arg = obs, col = "#0d9488", border = "#115e59", las = 1,
xlab = "Observation", ylab = sprintf("Squared deviation (%s^2)", units))
abline(h = var_s, col = "#c2410c", lwd = 2.2, lty = 2)
title(main = sprintf("Squared deviations, s^2 = %.2f", var_s), adj = 0, cex.main = 1)
dev.off()
cat("\nSaved variance_plot.png\n")
# ---- 5. Comparing groups (optional) ------------------------
# placebo <- c(142, 138, 150, 145, 136, 155, 141, 148, 139, 152, 144, 147)
# treatment <- c(128, 131, 126, 135, 129, 133, 127, 130, 132, 128, 134, 129)
# var.test(placebo, treatment) # F-test, two groups
# y <- c(placebo, treatment)
# g <- factor(rep(c("Placebo", "Treatment"), each = 12))
# bartlett.test(y ~ g) # Bartlett's test
# z <- abs(y - ave(y, g, FUN = median)) # Brown-Forsythe Levene by hand
# anova(lm(z ~ g)) # same as car::leveneTest(y ~ g)
Expected output for the leaf data: sample variance 17.5958, population variance 16.4961, SD 4.1947, 95% CI for the variance 9.6018 to 42.1481. These match Sections 7, 9 and 11.
10.2 What each part does
| Line or function | What it does, and why it is there |
|---|---|
| x <- c(...) | Builds the numeric vector. Swap in read.csv("data.csv")$col to load a file. |
| x[!is.na(x)] | Removes missing values. var() returns NA if even one value is missing. |
| dev, sq, ss | The three steps of the hand calculation: deviation, squared deviation and sum of squares. |
| var(x) | The sample variance with n − 1. It matches Excel's VAR.S. |
| var_s * (n - 1) / n | Converts to the population variance, because R has no built-in population variance. |
| qchisq() | Chi-square critical values with n − 1 df, used for the confidence interval. |
| ss / chi_hi, ss / chi_lo | The lower and upper limits. Dividing by the larger critical value gives the lower limit. |
| share | The largest single squared deviation as a percent of SS. Over 50% means one value drives the variance. |
| png(..., res = 300) | Opens a 300 dpi file for print-quality output. |
| segments() | Draws each deviation as a vertical line from the mean to the value. |
| barplot(sq) | Shows the squared deviations; the dashed line at the variance is their average (with n − 1). |
| dev.off() | Closes the file. Forgetting it leaves an empty or locked PNG. |
| var.test(), bartlett.test() | Two-group F-test and k-group Bartlett's test, both in base R. |
| abs(y - ave(y, g, FUN = median)) | The Brown-Forsythe trick: an ANOVA on these absolute deviations is Levene's test with the median centre. |
10.3 What the figure shows
The left panel plots each value in order. The dashed orange line is the mean, the shaded band is the mean plus or minus one SD, and each purple line is a deviation. The right panel squares those deviations into bars. The dashed line is the sample variance. You can see at once which values contribute most: the 61 mm leaf makes the tallest bar, about 28% of the total.
If one bar towers over all the others, a single value is driving your variance. Check it before you report anything.
10.4 Common R problems and fixes
| Symptom | Cause | Fix |
|---|---|---|
var(x) returns NA | Missing values in the vector | Use var(x, na.rm = TRUE) or clean first |
| Need the population variance | R's var() is always n − 1 | var(x) * (length(x) - 1) / length(x) |
var(df) returns a matrix | On a data frame it gives the covariance matrix | Use var(df$col) or sapply(df, var) |
| Differs from Python | NumPy defaults to ddof = 0 | Use np.var(x, ddof=1) in Python |
| Levene differs from SPSS | SPSS centres on the mean | car::leveneTest(y ~ g, center = mean) |
| PNG is empty | dev.off() not run | Run the whole script, including the last lines |
| Variance by group | Need one value per group | tapply(df$value, df$group, var) |
10.5 Useful one-liners
| You want | R code |
|---|---|
| Sample variance | var(x) |
| Population variance | mean((x - mean(x))^2) |
| Variance from SD | sd_value^2 |
| Coefficient of variation, % | sd(x) / mean(x) * 100 |
| Variance by group | tapply(df$value, df$group, var) |
| F-test, two groups | var.test(a, b) |
| Bartlett's test | bartlett.test(value ~ group, data = df) |
| Levene's test | car::leveneTest(value ~ group, data = df) |
| Variance of a distribution | sum(p * (v - sum(p * v))^2) |
📈 11. How to Calculate Variance in Python
In Python the sample variance is np.var(x, ddof=1). The ddof=1 part matters: without it NumPy returns the population variance. The script below is complete and runnable. It works through each step, prints both variances, the confidence interval and a plain-English check, and saves one 300 dpi figure.
x = np.array([...]) line.Install with pip install numpy scipy matplotlib if you do not already have them.
11.1 The complete script
Python 3, saves variance_plot.png
# ============================================================
# Variance calculator: sample and population variance, SD,
# 95% CI for the variance, and one publication-ready figure
# StatsUnlock - https://statsunlock.com/variance-calculator/
# ============================================================
import numpy as np
import matplotlib
matplotlib.use("Agg") # save to file, no window needed
import matplotlib.pyplot as plt
from scipy import stats
# ---- 1. Your data ------------------------------------------
# Replace with your own values, or read a CSV:
# import pandas as pd
# x = pd.read_csv("data.csv")["column_name"].dropna().to_numpy()
x = np.array([52, 48, 55, 61, 47, 50, 58, 53,
49, 56, 51, 54, 46, 57, 50, 52], dtype=float)
x = x[~np.isnan(x)] # drop missing values
label = "Leaf length"
units = "mm"
conf = 0.95
# ---- 2. Variance, step by step -----------------------------
n = len(x)
mean_x = x.mean()
dev = x - mean_x # deviations, they sum to 0
sq = dev ** 2 # squared deviations
ss = sq.sum() # sum of squares
var_s = np.var(x, ddof=1) # sample variance, n - 1 (Excel VAR.S)
var_p = np.var(x, ddof=0) # population variance, n (Excel VAR.P)
sd_s = np.sqrt(var_s)
sd_p = np.sqrt(var_p)
cv = sd_s / mean_x * 100
# ---- 3. Confidence interval for the variance ---------------
a = 1 - conf
chi_lo = stats.chi2.ppf(a / 2, n - 1)
chi_hi = stats.chi2.ppf(1 - a / 2, n - 1)
ci_lo, ci_hi = ss / chi_hi, ss / chi_lo
print(f"n = {n}")
print(f"mean = {mean_x:.4f}")
print(f"sum of squares = {ss:.4f}")
print(f"sample variance = {var_s:.4f} (n - 1)")
print(f"population variance = {var_p:.4f} (n)")
print(f"sample SD = {sd_s:.4f} population SD = {sd_p:.4f}")
print(f"CV = {cv:.2f}%")
print(f"{conf:.0%} CI for variance = {ci_lo:.4f} to {ci_hi:.4f}")
print(f"{conf:.0%} CI for SD = {np.sqrt(ci_lo):.4f} to {np.sqrt(ci_hi):.4f}")
share = sq.max() / ss * 100
verdict = ("one value dominates, check it" if share > 50
else "no single value dominates the variance")
print(f"largest share of SS = {share:.1f}% -> {verdict}")
# ---- 4. One figure, two panels -----------------------------
order = np.arange(1, n + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.2))
# Left: each value, the mean, and its deviation
ax1.axhspan(mean_x - sd_s, mean_x + sd_s, color="#16a34a", alpha=0.10,
label="mean +/- 1 SD")
ax1.vlines(order, mean_x, x, color="#9333ea", lw=1.4, zorder=2)
ax1.scatter(order, x, color="#2563eb", s=36, zorder=3, label="value")
ax1.axhline(mean_x, color="#c2410c", lw=2, ls="--", label=f"mean = {mean_x:.2f}")
ax1.set_xlabel("Observation")
ax1.set_ylabel(f"{label} ({units})")
ax1.set_title("Deviations from the mean", loc="left", fontweight="bold")
ax1.legend(frameon=False, fontsize=8, ncol=3, loc="upper center",
bbox_to_anchor=(0.5, -0.17))
# Right: squared deviations with the variance line
ax2.bar(order, sq, color="#0d9488", edgecolor="#115e59")
ax2.axhline(var_s, color="#c2410c", lw=2, ls="--",
label=f"sample variance = {var_s:.2f}")
ax2.set_xlabel("Observation")
ax2.set_ylabel(f"Squared deviation ({units}\u00b2)")
ax2.set_title("Squared deviations", loc="left", fontweight="bold")
ax2.legend(frameon=False, fontsize=8, loc="upper center",
bbox_to_anchor=(0.5, -0.17))
for ax in (ax1, ax2):
ax.spines[["top", "right"]].set_visible(False)
fig.suptitle(f"{label}: n = {n}, s\u00b2 = {var_s:.2f} {units}\u00b2, SD = {sd_s:.2f} {units}",
x=0.01, ha="left", fontsize=11)
fig.tight_layout()
fig.savefig("variance_plot.png", dpi=300, bbox_inches="tight")
print("\nSaved variance_plot.png")
Printed output for the leaf data: sample variance 17.5958, population variance 16.4961, SD 4.1947, CV 8.00%, 95% CI for the variance 9.6018 to 42.1481, and largest share of SS 27.8%.
11.2 What each part does
| Line or function | What it does, and why it is there |
|---|---|
| matplotlib.use("Agg") | Saves figures without opening a window, so the script also runs on servers. |
| x[~np.isnan(x)] | Drops missing values, which would otherwise turn every result into nan. |
| dev, sq, ss | Deviation, squared deviation and sum of squares, exactly as in the hand calculation. |
| np.var(x, ddof=1) | Sample variance. ddof is "delta degrees of freedom": the divisor is n − ddof. |
| np.var(x, ddof=0) | Population variance, NumPy's default. |
| stats.chi2.ppf() | Chi-square critical values for the confidence interval. |
| ax1.vlines() | Draws each deviation from the mean to the value. |
| ax2.bar(order, sq) | The squared deviations; the dashed line is the variance. |
| dpi=300, bbox_inches="tight" | Print-quality output with nothing cut off at the edges. |
11.3 What the figure shows
The figure is the same two-panel design as the R version: deviations on the left and squared deviations on the right. Looking at the squares is the fastest way to see why variance reacts so strongly to extreme values. A value twice as far from the mean makes a bar four times as tall.
11.4 Common Python problems and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Variance smaller than Excel's VAR.S | NumPy defaults to ddof = 0 | Always pass ddof=1 for a sample |
| Pandas and NumPy disagree | Pandas defaults to ddof = 1, NumPy to 0 | Set ddof explicitly in both |
Result is nan | A NaN in the array | Use np.nanvar(x, ddof=1) or drop missing values first |
| Levene differs from SPSS | SciPy centres on the median by default | stats.levene(a, b, center="mean") to match SPSS |
statistics.variance error | Fewer than two values | The sample variance needs n ≥ 2 |
| Figure blurry | Default 100 dpi | Use dpi=300 or save as PDF or SVG |
11.5 Useful one-liners
| You want | Python code |
|---|---|
| Sample variance | np.var(x, ddof=1) |
| Population variance | np.var(x) |
| Standard library | statistics.variance(x), statistics.pvariance(x) |
| Variance by group | df.groupby("group")["value"].var() |
| Levene's test | stats.levene(a, b, c) |
| Bartlett's test | stats.bartlett(a, b, c) |
| Variance of a distribution | np.sum(p * (v - np.sum(p * v))**2) |
| Bootstrap CI for variance | stats.bootstrap((x,), lambda s: np.var(s, ddof=1)).confidence_interval |
ddof=1 in Python.📋 12. Reference Tables
12.1 Sample or population variance?
| Your data | Use | Divide SS by | Excel |
|---|---|---|---|
| A sample, and you want to describe a larger group | Sample variance s² | n − 1 | VAR.S |
| Every member of the group was measured | Population variance σ² | n | VAR.P |
| Probability distribution with known P(x) | Var(X) = ΣP(x)(x − μ)² | No division (weights sum to 1) | SUMPRODUCT |
| Frequency table of values and counts | Weighted sample variance | Σf − 1 | SUMPRODUCT |
| Not sure | Sample variance | n − 1 | VAR.S |
Conclusion: in research, the sample variance is almost always correct. The population version is for complete counts, such as every machine in one factory.
12.2 Chi-square critical values for the variance confidence interval
| df = n − 1 | χ² 0.025 | χ² 0.975 | χ² 0.005 | χ² 0.995 |
|---|---|---|---|---|
| 1 | 0.0010 | 5.0239 | 0.0000 | 7.8794 |
| 2 | 0.0506 | 7.3778 | 0.0100 | 10.5966 |
| 3 | 0.2158 | 9.3484 | 0.0717 | 12.8382 |
| 4 | 0.4844 | 11.1433 | 0.2070 | 14.8603 |
| 5 | 0.8312 | 12.8325 | 0.4117 | 16.7496 |
| 7 | 1.6899 | 16.0128 | 0.9893 | 20.2777 |
| 9 | 2.7004 | 19.0228 | 1.7349 | 23.5894 |
| 11 | 3.8157 | 21.9200 | 2.6032 | 26.7568 |
| 15 | 6.2621 | 27.4884 | 4.6009 | 32.8013 |
| 19 | 8.9065 | 32.8523 | 6.8440 | 38.5823 |
| 24 | 12.4012 | 39.3641 | 9.8862 | 45.5585 |
| 29 | 16.0471 | 45.7223 | 13.1211 | 52.3356 |
Conclusion: for a 95% interval, divide SS by the 0.975 value for the lower limit and by the 0.025 value for the upper limit. For the leaf data, df = 15: 263.9375 ÷ 27.4884 = 9.60 and 263.9375 ÷ 6.2621 = 42.15. Use the 0.005 and 0.995 columns for 99%.
12.3 How wide is a 95% CI for the variance? (as a multiple of s²)
| n | Lower limit | Upper limit | Upper ÷ lower | σ² ÷ s² = (n − 1) ÷ n |
|---|---|---|---|---|
| 5 | 0.359 × s² | 8.257 × s² | 23.0 | 0.8000 |
| 10 | 0.473 × s² | 3.333 × s² | 7.0 | 0.9000 |
| 16 | 0.546 × s² | 2.395 × s² | 4.4 | 0.9375 |
| 30 | 0.634 × s² | 1.807 × s² | 2.9 | 0.9667 |
| 50 | 0.698 × s² | 1.553 × s² | 2.2 | 0.9800 |
| 100 | 0.771 × s² | 1.349 × s² | 1.7 | 0.9900 |
Conclusion: a variance from 5 values could be anything from about a third to eight times the true value. You need around 50 values before the interval shrinks to roughly ±50%. The last column shows the population variance shrinks towards the sample variance as n grows.
12.4 Two-sided F critical values (α = 0.05) for comparing two variances
| df₂ (smaller variance) ↓ / df₁ (larger variance) → | 5 | 9 | 11 | 15 | 20 | 30 |
|---|---|---|---|---|---|---|
| 5 | 7.146 | 6.681 | 6.568 | 6.428 | 6.329 | 6.227 |
| 9 | 4.484 | 4.026 | 3.912 | 3.769 | 3.667 | 3.560 |
| 11 | 4.044 | 3.588 | 3.474 | 3.330 | 3.226 | 3.118 |
| 15 | 3.576 | 3.123 | 3.008 | 2.862 | 2.756 | 2.644 |
| 20 | 3.289 | 2.837 | 2.721 | 2.573 | 2.464 | 2.349 |
| 30 | 3.026 | 2.575 | 2.458 | 2.307 | 2.195 | 2.074 |
Conclusion: put the larger variance on top. If the ratio is bigger than the table value, the variances differ at the 0.05 level (two-sided). With 10 values per group (df 9 and 9) the ratio must exceed 4.03, which shows how hard it is to detect unequal variances in small samples.
12.5 How one outlier inflates the variance
| Dataset | Sample variance | SD | Largest value's share of SS | Verdict |
|---|---|---|---|---|
| 8, 9, 10, 11, 12 | 2.50 | 1.58 | 40% | Balanced |
| 8, 9, 10, 11, 20 | 23.30 | 4.83 | 76% | One value dominates |
| 8, 9, 10, 11, 60 | 511.30 | 22.61 | 80% | Outlier drives the variance |
Conclusion: changing one value from 12 to 60 multiplied the variance by more than 200. Squaring makes the variance the least robust common statistic.
12.6 Coefficient of variation: rough interpretation bands
| CV | Spread | Typical examples |
|---|---|---|
| Under 10% | Low | Lab assays, machine fills, repeated body measurements |
| 10% to 30% | Moderate | Exam scores, crop yields, tree diameters in one stand |
| Over 30% | High | Income, animal counts, stock returns, skewed data |
Conclusion: these bands are a guide, not a law. Judge your CV against values published in your own field, and never use CV for data that can be negative.
12.7 How to find variance on a calculator
| Calculator | Keys | What you get |
|---|---|---|
| TI-83 / TI-84 | STAT → 1:Edit, type data in L1. STAT → CALC → 1:1-Var Stats → ENTER | Sx and σx. Square Sx for the sample variance, σx for the population variance |
| TI-84 Plus CE (direct) | 2nd LIST → MATH → 8:variance( → L1 → ENTER | The sample variance directly |
| Casio fx-991 / fx-82 | MENU → Statistics → 1-Variable, enter data, OPTN → 1-Variable Calc | sx and σx; square them |
| Google Sheets | =VAR.S(A2:A17) | Sample variance |
| This page | Paste data, press Calculate Variance | Both variances, both SDs, CI and tests |
Conclusion: most handheld calculators give the standard deviation, not the variance. Square the right one: Sx (or sx) for a sample, σx for a population.
📈 13. Example Results
Eight worked examples show what typical, clear, borderline, null and problem results look like, and how to write each one up.
The classic 2, 4, 4, 4, 5, 5, 7, 9
The dataset every statistics course uses.
Eight values with a mean of exactly 5. The textbook asks for both the sample and the population variance.
| Statistic | Value | Note |
|---|---|---|
| Sum of squares | 32.0000 | 9 + 1 + 1 + 1 + 0 + 0 + 4 + 16 |
| Population variance | 4.0000 | 32 ÷ 8 |
| Sample variance | 4.5714 | 32 ÷ 7 |
| Population SD | 2.0000 | √4 |
| Sample SD | 2.1381 | √4.5714 |
| CV | 42.76% | High relative spread |
| 95% CI for variance | 2.00 to 18.94 | Wide, because n = 8 |
What it means: the two answers differ only in the divisor. If these 8 values are the whole population, the variance is 4 and the SD is exactly 2. If they are a sample, the variance is 4.57. The single value 9 supplies half the sum of squares, a reminder of how much the largest deviation matters.
How to write it: "Scores had a sample variance of 4.57 (SD = 2.14, M = 5.00, n = 8)."
Two bottling machines
Variance is the quality measure: same mean, very different precision.
Ten bottles from each machine, target 500 ml. Both machines average almost exactly 500 ml.
| Statistic | Value | Note |
|---|---|---|
| Mean A / B | 500.03 / 500.07 ml | Nearly identical |
| Sample variance A | 0.0357 ml² | SD 0.19 ml |
| Sample variance B | 1.7334 ml² | SD 1.32 ml |
| Variance ratio (F-max) | 48.60 | Far above 4 |
| F-test | F(9, 9) = 48.60, p < .001 | Excel F.TEST |
| Levene (median) | W(1, 18) = 46.45, p < .001 | Robust test |
| Bartlett | χ²(1) = 21.64, p < .001 | Normal-theory test |
What it means: the averages say both machines are fine. The variances say otherwise. Machine B is about 49 times more variable, and all three tests agree the difference is real. A t-test on the means would miss this completely.
How to write it: "Fill volume was far more variable for Machine B (s² = 1.73 ml²) than Machine A (s² = 0.036 ml²), Levene's W(1, 18) = 46.45, p < .001."
Weight loss under two programmes
A three-fold variance ratio that does not quite reach significance.
Kilograms lost after 12 weeks, 10 people per programme. The means are almost the same.
| Statistic | Value | Note |
|---|---|---|
| Mean, diet only / diet + exercise | 5.32 / 5.45 kg | Similar |
| Sample variance, diet only | 4.1951 kg² | SD 2.05 kg |
| Sample variance, diet + exercise | 1.2806 kg² | SD 1.13 kg |
| F-test | F(9, 9) = 3.28, p = .092 | Below the 4.03 needed |
| Levene (median) | W(1, 18) = 3.63, p = .073 | Not significant at .05 |
What it means: the diet-only group looks three times as variable, but neither test reaches 0.05. With only 10 people per group, the study cannot tell whether this is a real difference or chance. The ratio is in the grey zone of 2 to 4, so using Welch's t-test for any comparison of means is still the safe choice.
How to write it: "Variability tended to be higher with diet only (s² = 4.20) than with diet plus exercise (s² = 1.28), but the difference was not significant, Levene's W(1, 18) = 3.63, p = .073."
Morning versus evening test scores
Different means, but the same spread.
Quiz scores for a morning and an evening class, 10 students each. You need to know if equal variances can be assumed for a t-test.
| Statistic | Value | Note |
|---|---|---|
| Mean, morning / evening | 25.9 / 30.0 | The means differ |
| Sample variance, morning | 6.7667 | SD 2.60 |
| Sample variance, evening | 7.7778 | SD 2.79 |
| F-test | F(9, 9) = 1.15, p = .84 | Ratio near 1 |
| Levene (median) | W(1, 18) = 0.02, p = .89 | No evidence of difference |
What it means: the classes differ in level but not in spread. The variance ratio is only 1.15, and Levene's test is far from significant. Equal variances are a reasonable assumption, although Welch's t-test would give almost the same answer anyway.
How to write it: "Variances did not differ between classes (morning s² = 6.77, evening s² = 7.78), Levene's W(1, 18) = 0.02, p = .886."
VO2 max in six elite rowers
A precise-looking variance with a huge interval.
Six rowers from one squad. The coach wants to know how consistent their aerobic fitness is.
| Statistic | Value | Note |
|---|---|---|
| Mean | 61.75 ml/kg/min | |
| Sample variance | 5.9390 | (ml/kg/min)² |
| Sample SD | 2.4370 | CV 3.95% |
| 95% CI for variance | 2.3140 to 35.7250 | df = 5 |
| 95% CI for SD | 1.5212 to 5.9770 | Square roots of the limits |
What it means: the squad looks very consistent, with a CV under 4%. But the true variance could be anywhere from 2.3 to 35.7, a 15-fold range. With n = 6, report the interval along with the estimate so nobody over-reads the precision.
How to write it: "VO2 max varied little among rowers (s² = 5.94, SD = 2.44, n = 6), although the 95% CI for the variance was wide [2.31, 35.73]."
Exam scores in two large regions
With 3,000 students per group, a tiny difference becomes "significant".
National exam scores from two regions, 3,000 students each. Only the summary statistics are available.
| Statistic | Value | Note |
|---|---|---|
| Sample variance, region 1 | 100.00 | SD 10.00 |
| Sample variance, region 2 | 108.00 | SD 10.39 |
| Variance ratio | 1.08 | Far below the rule-of-thumb 4 |
| F-test | F(2999, 2999) = 1.08, p = .035 | Significant at .05 |
| Difference in SD | 0.39 points | Practically nothing |
What it means: the F-test is significant only because the samples are huge. The SDs differ by less than half a point on a 100-point exam, which matters to no one. Always look at the size of the ratio, not just the p-value.
How to write it: "Although the variance ratio was statistically significant, F(2999, 2999) = 1.08, p = .035, the SDs (10.0 vs 10.4) were practically equivalent."
Monthly income with one high earner
One value supplies 91% of the variance.
Monthly income in thousands for 12 people. Eleven earn between 2.7 and 4.1; one earns 24.5.
| Statistic | Value | Note |
|---|---|---|
| Mean / median | 5.07 / 3.35 | Mean pulled up |
| Sample variance, all 12 | 37.6261 | SD 6.13 |
| Outlier's share of SS | 91.2% | One value dominates |
| Sample variance, without 24.5 | 0.1900 | SD 0.44, n = 11 |
| IQR | 0.675 | Robust spread |
| CV | 121.07% | Misleading here |
What it means: the variance of 37.6 does not describe the typical person at all. Remove one value and it falls to 0.19, nearly 200 times smaller. The chi-square interval is also invalid here, because the data are far from normal. Report the median and IQR, and the variance with and without the outlier if you need it.
How to write it: "Income was highly skewed (median = 3.35, IQR = 0.68); one participant accounted for 91% of the total sum of squares, so the variance (37.63) is reported for completeness only."
Tree diameter at three forest sites
Variance as a measure of stand structure.
Diameter at breast height (cm) in three plots: a natural stand (A), a mixed-age stand (B) and an even-aged plantation (C).
| Statistic | Value | Note |
|---|---|---|
| Means A / B / C | 36.92 / 39.80 / 37.82 cm | Similar sizes |
| Sample variances | 22.63 / 202.18 / 3.36 cm² | Very different |
| CV A / B / C | 12.9% / 35.7% / 4.8% | Moderate, high, low |
| F-max | 60.11 | B ÷ C |
| Levene (median) | W(2, 30) = 20.20, p < .001 | Robust test |
| Bartlett | χ²(2) = 31.84, p < .001 | Agrees |
What it means: mean diameter is similar across sites, but the spread tells the ecological story. The mixed-age stand has trees of every size, the plantation trees were all planted at once. Any ANOVA on the means here must use Welch's version, because the variances differ by a factor of 60.
How to write it: "DBH variance differed strongly among sites (A: 22.6, B: 202.2, C: 3.4 cm²), Levene's W(2, 30) = 20.20, p < .001, so means were compared with Welch's ANOVA."
🧪 14. Data Collection Protocol
Study design: variance assumes a set of independent measurements of one quantity on an interval or ratio scale. To compare variances, each group must be measured with the same instrument and the same method.
- Decide why you need the variance. Describing one group, checking an assumption before a t-test or ANOVA, and testing whether one group is more consistent are different aims. Write the aim down first.
- Define the population and the unit. Decide whether you are sampling from a larger group (sample variance) or measuring every member (population variance).
- Fix the instrument, units and resolution. Measurement error adds directly to the variance. A ruler marked only in centimetres adds spread a millimetre scale would not.
- Calibrate before you start and record it. Drift during a study inflates the variance for reasons that have nothing to do with the subject.
- Randomise the selection and the order of measurement. Measuring all of one group first can mix time effects into group differences in spread.
- Keep units independent. Repeat readings of the same plant or person are not independent. Average them first, or use a mixed model, otherwise the variance looks smaller than it really is.
- Plan the sample size for the precision you need. Use Table 12.3: at least 30 per group if you want the variance within roughly ±50%, and at least 20 per group to have a fair chance of detecting a two-fold difference in variance.
- Record missing values as blanks, never as zero. A zero creates a large false squared deviation.
- Write the outlier rule in advance. Because variance squares distances, decide before you see the data how you will check and handle extreme values.
- Store data one column per group, as shown below, ready to paste or upload here.
| Machine A (ml) | Machine B (ml) | Machine C (ml) |
|---|---|---|
| 500.2 | 501.2 | 499.6 |
| 499.8 | 498.6 | 500.4 |
| 500.1 | 500.9 | 500.1 |
One column per group, one row per unit, numbers only below the header. Blank cells are ignored, so groups can have different sizes.
Minimum sample: the sample variance needs at least 2 values, but anything under 10 per group gives a very rough estimate. Equal-variance tests need at least 5 per group to be meaningful.
Pre-registration: state the variance formula (n − 1 or n), the equal-variance test and its alpha, the outlier rule, and what you will do if variances differ, such as switching to Welch's test.
Common collection mistakes:
- Recording missing values as zero, which inflates the variance.
- Changing instruments or observers part way through.
- Treating repeated readings of one unit as separate observations.
- Rounding too much at collection, which hides real variation.
- Pooling two different populations into one column, which inflates the variance.
🎯 15. When to Use This Variance Calculator
This free variance calculator is designed for students, teachers, researchers and analysts who need the variance and standard deviation of one or more groups, with the working shown.
Use it when:
- ✓ You need the sample or population variance of numeric data.
- ✓ You want to check equal variances before a t-test or ANOVA.
- ✓ You want to know which group, machine, method or site is more consistent.
- ✓ You need a confidence interval for a variance or SD.
- ✓ You need to show the step-by-step calculation for homework or a report.
- ✓ You want to convert between SD and variance, or find a percent variance.
Do not use it when:
- ✗ The data are categories or ranks. Use frequencies or the median and IQR.
- ✗ The data are heavily skewed and you want a typical spread. Use the IQR or MAD.
- ✗ You want to compare group means. Use a t-test or an ANOVA calculator (analysis of variance compares means, not variances).
- ✗ The data are repeated measures or clustered. Use a mixed model to split the variance into its parts.
- ✗ You need a two-way analysis of variance table. That is a separate design with two factors.
Real-world examples:
- Manufacturing: comparing the variance of fill volume between machines to decide which needs servicing.
- Finance: the variance of monthly returns as a measure of risk for a portfolio.
- Ecology: comparing the variance of tree size between natural and planted stands.
- Education: checking whether a new method makes student results more consistent.
Design guidance: if your main question is about spread, plan the sample size around the variance, not the mean, because variances need larger samples to estimate well.
Decision tree:
| Question | If yes | If no |
|---|---|---|
| Is the data numeric on an interval or ratio scale? | Go on | Use frequencies or the median and IQR |
| Do you want the spread of one group? | Sample variance, SD and CI | Go on |
| Do you want to compare spread between groups? | Levene's test (any data) or Bartlett's (normal data) | Go on |
| Do you want to compare means between groups? | t-test (2 groups) or ANOVA (3 or more), Welch's version if variances differ | Descriptive statistics only |
🔧 16. Troubleshooting and Common Errors
My variance is much bigger than I expected
Cause: one extreme value, a typing error such as 520 for 52, or a missing value entered as 0.
Fix: look at the "largest share of SS" line in the checks table and at Chart 2. Correct typos, remove fake zeros, and press Calculate again.
My answer differs from Excel
Cause: sample versus population formula, or a different number of values.
Fix: compare n first. Then compare with VAR.S for the sample variance and VAR.P for the population variance; this page shows both.
My answer differs from Python NumPy
Cause: np.var defaults to the population variance (ddof = 0).
Fix: use np.var(x, ddof=1) for the sample variance.
My TI-84 does not show a variance
Cause: 1-Var Stats shows standard deviations, Sx and σx.
Fix: square Sx for the sample variance or σx for the population variance, or use LIST → MATH → variance(.
Some values were ignored
Cause: text, currency symbols, units or a comma used as a decimal mark.
Fix: the warning box under the settings lists every skipped entry. Use a full stop for decimals, remove symbols and units, and run again.
The variance shows as undefined
Cause: a group has fewer than 2 numeric values, so n − 1 is 0.
Fix: add more values or remove that group.
The variance is 0
Cause: every value in the group is identical.
Fix: this is correct. Check that you pasted the right column if you expected spread.
Levene's and Bartlett's tests disagree
Cause: Bartlett's test is sensitive to non-normal data and can flag skew as unequal variance.
Fix: check the skewness column in the checks table. If the data are skewed, trust Levene's (Brown-Forsythe) result.
Levene's p-value differs from SPSS
Cause: SPSS centres on the mean; this page, R's car package and SciPy centre on the median by default.
Fix: state which version you used. Both are valid; the median version is more robust.
The confidence interval looks far too wide
Cause: small sample size. The interval for a variance is naturally wide.
Fix: nothing is wrong. Table 12.3 shows how the width shrinks with n. Collect more data if you need more precision.
Excel's ToolPak F-test p-value is half of this page's
Cause: the ToolPak reports a one-tailed p-value; this page and F.TEST report two-tailed.
Fix: double the ToolPak value, or use F.TEST.
The charts do not appear
Cause: the chart library was blocked, or the calculator has not been run.
Fix: allow cdnjs.cloudflare.com and press Calculate Variance. All tables and the working still appear without the charts.
⚖ 17. Assumptions and Limitations
Assumptions
- Numeric data on an interval or ratio scale. Check: the numbers measure an amount. If violated, for example with ranks or codes, the variance has no clear meaning.
- Independent observations. Check: each value comes from a different unit. If violated, the variance is usually underestimated, because repeated readings of one unit are similar.
- A random, representative sample. Check: the sampling method. If violated, the variance can be biased in either direction, often too small when the sample is more uniform than the population.
- Normal data, for the confidence interval and Bartlett's test. Check: the skewness and kurtosis in the checks table and Chart 4. If violated with heavy tails, the CI is too narrow and Bartlett's test gives too many false positives.
- No gross errors or unchecked outliers. Check: the largest share of SS. If violated, the variance is inflated, sometimes many times over.
- Same measurement method in every group, for comparisons. Check: the protocol. If violated, a group measured less precisely shows an inflated variance.
Limitations
- The variance is not robust: one extreme value can dominate it. Use the IQR, the MAD or a trimmed variance for messy data.
- It is in squared units, which are hard to explain. Report the SD for descriptive purposes.
- The chi-square interval depends strongly on normality. For skewed data, use a bootstrap interval in R or Python (Section 11.5).
- The F-test is not robust to non-normal data. Prefer Levene's (Brown-Forsythe) test, which this page shows first.
- Equal-variance tests have low power with small groups. A non-significant result does not prove the variances are equal.
- This tool treats data as a simple random sample. Survey designs with weights or clusters need design-based variance estimators.
- It does not compute ANOVA tables. For comparing means, use a t-test or ANOVA tool, choosing Welch's version when variances differ.
🏁 18. Conclusion
Your results: run the analysis above to see your own conclusion here. Your sample variance will show as s² = ___ with SD = ___ and n = ___.
A variance calculator answers a simple question: how far, on average, do the values sit from their mean? The steps are always the same. Find the mean, subtract it from every value, square the differences, add them up and divide. The only real choice is the divisor: n − 1 for a sample, which is almost every research situation, or n for a complete population.
The number itself is in squared units, so in most writing the standard deviation is the friendlier way to describe spread. The variance earns its place elsewhere. It is what statistical tests and models work with, it adds up neatly across independent sources of variation, and comparing variances tells you which group, method or machine is more consistent.
Three habits make variance results trustworthy. First, always say whether you used the sample or population formula and give n. Second, look at the squared deviations, because one extreme value can make up most of the variance. Third, remember that a variance from a small sample is uncertain: the confidence interval shows how much, and it is often wider than people expect.
When you compare groups, start with Levene's test because it works on real, imperfect data, and use the result to choose the right test of means, such as Welch's t-test or Welch's ANOVA. A difference in spread can also be a finding in its own right.
Paste your numbers into the calculator above, check the step-by-step table and the charts, copy a reporting template from Section 5, and come back to this variance calculator whenever you need the sample variance, population variance or standard deviation with every step shown.
❓ 19. Frequently Asked Questions
How do you calculate variance?
Find the mean, subtract it from each value, square each difference, and add the squares to get the sum of squares. Divide by n − 1 for a sample variance or by n for a population variance. For 2, 4, 4, 4, 5, 5, 7, 9 the sum of squares is 32, so the sample variance is 32 ÷ 7 = 4.57 and the population variance is 32 ÷ 8 = 4.
What is the formula for variance?
Sample variance is s² = Σ(x − x̄)² ÷ (n − 1). Population variance is σ² = Σ(x − μ)² ÷ N. Both use the same sum of squared deviations; only the divisor changes.
How do you calculate sample variance?
Add up the squared deviations from the sample mean and divide by n − 1. Dividing by n − 1 instead of n, called Bessel's correction, removes the bias that comes from measuring spread around the sample's own mean.
How do you calculate population variance?
Add up the squared deviations from the population mean and divide by N, the total number of values. Use it only when your data include every member of the group you want to describe.
What is the difference between sample and population variance?
Only the divisor. Sample variance divides by n − 1 and estimates the variance of a larger population. Population variance divides by n and describes a group you measured completely. The sample variance is always slightly larger, by a factor of n ÷ (n − 1).
How do you calculate variance and standard deviation?
Calculate the variance first, then take its square root to get the standard deviation. For the leaf data on this page, the sample variance is 17.5958 mm² and the standard deviation is √17.5958 = 4.1947 mm.
How do you calculate variance from standard deviation?
Square the standard deviation. An SD of 4.1947 gives a variance of 4.1947² = 17.5958. Use the quick converter under the Calculate button to do this instantly.
How do you calculate standard deviation from variance?
Take the square root of the variance. A variance of 25 gives an SD of 5. The SD is in the same units as the data, which is why it is easier to explain than the variance.
How do you calculate variance in Excel?
Use =VAR.S(A2:A17) for the sample variance and =VAR.P(A2:A17) for the population variance. For a confidence interval, use =DEVSQ for the sum of squares and divide by CHISQ.INV. Section 9 shows every step with spreadsheet screenshots.
How do you calculate variance in R?
Use var(x) for the sample variance. R has no population variance function, so use var(x) * (n − 1) / n. For comparing groups, use var.test(), bartlett.test() or car::leveneTest(). Section 10 has a complete runnable script.
How do you calculate variance in Python?
Use np.var(x, ddof=1) for the sample variance and np.var(x) for the population variance. NumPy defaults to the population version, which surprises many users. Pandas .var() defaults to the sample version. Section 11 has a complete script.
How do you calculate variance on a TI-84?
Enter data in L1, then press STAT, CALC, 1-Var Stats. The TI-84 shows Sx and σx, which are standard deviations, so square Sx for the sample variance. Newer models also have LIST, MATH, variance( for the sample variance directly.
How do you calculate percent variance?
Subtract the expected or budget value from the actual value, divide by the absolute expected value, and multiply by 100. A budget of 1200 against an actual 1350 is (1350 − 1200) ÷ 1200 × 100 = 12.5%. This is a percent difference used in accounting, not a statistical variance.
How do you calculate the variance between two numbers?
For two numbers a and b, the sample variance is (a − b)² ÷ 2 and the population variance is (a − b)² ÷ 4. For 10 and 14 that gives 8 and 4. If you mean the percent difference between two numbers, use the percent variance formula instead.
How do you calculate the variance of a probability distribution?
Find the mean μ = Σx P(x), then Var(X) = ΣP(x)(x − μ)². For values 0, 1, 2, 3 with probabilities 0.1, 0.3, 0.4, 0.2, the mean is 1.7 and the variance is 0.81. The probability converter on this page does this for you.
What is the coefficient of variance?
Usually called the coefficient of variation (CV), it is the standard deviation divided by the mean, times 100. It shows spread as a percentage of the mean, so you can compare groups with different means or units. The leaf data have a CV of 8.00%.
Why do we divide by n − 1?
Because the deviations are measured from the sample mean, which is calculated from the same data and sits as close to them as possible. That makes the squared deviations slightly too small on average. Dividing by n − 1 instead of n corrects this, giving an unbiased estimate of the population variance.
Can variance be negative?
No. Variance is an average of squared numbers, and squares are never negative. The smallest possible variance is 0, which happens only when every value is the same. A negative result means there is a calculation error.
How do I test whether two variances are equal?
Use Levene's test, which is robust to non-normal data, or Bartlett's test if the data are normal. For exactly two groups, the F-test (Excel F.TEST) compares the ratio of the variances. This calculator runs all three automatically when you enter two or more groups.
Can I use this variance calculator for my thesis or published research?
Yes for checking hand calculations, teaching and exploring data. For formal submission, reproduce the numbers in R, Python, SPSS or SAS and cite that software. You can also cite this tool: StatsUnlock. (2026). Variance calculator. https://statsunlock.com/variance-calculator/
📑 20. Cite This Tool
StatsUnlock. (2026). Variance calculator [Interactive statistical tool]. https://statsunlock.com/variance-calculator/@misc{statsunlock_variance_2026, title={Variance Calculator}, author={{StatsUnlock}}, year={2026}, note={Interactive statistical tool}, url={https://statsunlock.com/variance-calculator/}}Dispersion was summarised using the StatsUnlock Variance Calculator (2026). For each group we report the sample variance using the n minus 1 denominator, the standard deviation, and a chi-square confidence interval for the variance. Homogeneity of variance was assessed with the median-centred Levene's (Brown-Forsythe) test.🔗 21. Related Tools
The square root of the variance, with sample and population versions and full steps.
Open the tool →The centre that every variance is measured from, plus the median, mode and other averages.
Open the tool →Compare spread between groups with different means or units as a percentage.
Open the tool →Quartiles and the IQR, the robust alternative when outliers inflate the variance.
Open the tool →90, 95 and 99% intervals for a mean, built from the standard deviation.
Open the tool →See how the variance and the sample size set the margin of error of a survey or mean.
Open the tool →Show the spread of several groups side by side and spot the outliers behind a large variance.
Open the tool →Check normality before trusting the chi-square interval or Bartlett's test.
Open the tool →📖 22. Glossary of Terms
| Term | Plain-English meaning |
|---|---|
| Bartlett's test | A test of equal variances across groups that works well only when the data are normal. |
| Bessel's correction | Dividing by n − 1 instead of n so the sample variance is not too small on average. |
| Brown-Forsythe test | The version of Levene's test that measures distances from each group's median. It is robust to skew. |
| Chi-square distribution | The distribution used to build a confidence interval for a variance from normal data. |
| Coefficient of variation (CV) | The standard deviation as a percentage of the mean. |
| Confidence interval | A range of values that likely contains the true population value, at a stated confidence level. |
| Degrees of freedom (df) | The number of values free to vary after the mean is fixed. For one variance, n − 1. |
| Deviation | How far one value is from the mean: x − x̄. Deviations always add up to zero. |
| F-max (Hartley's) | The largest group variance divided by the smallest. Above about 4, variances are clearly unequal. |
| F-test for variances | A test of two variances using their ratio. Sensitive to non-normal data. |
| Homogeneity of variance | The assumption that all groups have the same variance. Also called homoscedasticity. |
| Interquartile range (IQR) | The spread of the middle half of the data, Q3 minus Q1. Not affected by outliers. |
| Levene's test | A test of equal variances that is robust to non-normal data. |
| Median absolute deviation (MAD) | The median of the distances from the median. A robust measure of spread. |
| Outlier | A value far from the rest. Because distances are squared, outliers can dominate the variance. |
| Percent variance | In budgeting, the percent difference between an actual and an expected value. |
| Pooled variance | A weighted average of several group variances, used when they are assumed equal. |
| Population variance (σ²) | The variance of every member of a group, dividing by n. |
| Sample variance (s²) | The variance of a sample used to estimate a population, dividing by n − 1. |
| Standard deviation | The square root of the variance, in the original units of the data. |
| Standard error | The SD divided by √n. It describes how precise a mean is, not how spread out the data are. |
| Sum of squares (SS) | The total of all squared deviations from the mean. |
| Variance | The average squared distance of values from their mean. |
📚 23. References
The following peer-reviewed references support the methods used in this variance calculator: computing the variance accurately, confidence intervals, tests for equal variances, robust alternatives and good reporting practice.
- Altman, D. G., & Bland, J. M. (2005). Standard deviations and standard errors. BMJ, 331(7521), 903. https://doi.org/10.1136/bmj.331.7521.903
- Bartlett, M. S. (1937). Properties of sufficiency and statistical tests. Proceedings of the Royal Society of London. Series A, 160(901), 268–282. https://doi.org/10.1098/rspa.1937.0109
- Box, G. E. P. (1953). Non-normality and tests on variances. Biometrika, 40(3/4), 318–335. https://doi.org/10.1093/biomet/40.3-4.318
- Brown, M. B., & Forsythe, A. B. (1974). Robust tests for the equality of variances. Journal of the American Statistical Association, 69(346), 364–367. https://doi.org/10.1080/01621459.1974.10482955
- Chan, T. F., Golub, G. H., & LeVeque, R. J. (1983). Algorithms for computing the sample variance: Analysis and recommendations. The American Statistician, 37(3), 242–247. https://doi.org/10.1080/00031305.1983.10483115
- Conover, W. J., Johnson, M. E., & Johnson, M. M. (1981). A comparative study of tests for homogeneity of variances, with applications to the outer continental shelf bidding data. Technometrics, 23(4), 351–361. https://doi.org/10.1080/00401706.1981.10487680
- Cumming, G., Fidler, F., & Vaux, D. L. (2007). Error bars in experimental biology. Journal of Cell Biology, 177(1), 7–11. https://doi.org/10.1083/jcb.200611141
- Gastwirth, J. L., Gel, Y. R., & Miao, W. (2009). The impact of Levene's test of equality of variances on statistical theory and practice. Statistical Science, 24(3), 343–360. https://doi.org/10.1214/09-STS301
- Hartley, H. O. (1950). The maximum F-ratio as a short-cut test for heterogeneity of variance. Biometrika, 37(3/4), 308–312. https://doi.org/10.1093/biomet/37.3-4.308
- Hozo, S. P., Djulbegovic, B., & Hozo, I. (2005). Estimating the mean and variance from the median, range, and the size of a sample. BMC Medical Research Methodology, 5, 13. https://doi.org/10.1186/1471-2288-5-13
- Leys, C., Ley, C., Klein, O., Bernard, P., & Licata, L. (2013). Detecting outliers: Do not use standard deviation around the mean, use absolute deviation around the median. Journal of Experimental Social Psychology, 49(4), 764–766. https://doi.org/10.1016/j.jesp.2013.03.013
- Lim, T.-S., & Loh, W.-Y. (1996). A comparison of tests of equality of variances. Computational Statistics & Data Analysis, 22(3), 287–301. https://doi.org/10.1016/0167-9473(95)00054-2
- Ling, R. F. (1974). Comparison of several algorithms for computing sample means and variances. Journal of the American Statistical Association, 69(348), 859–866. https://doi.org/10.1080/01621459.1974.10480219
- Markowitz, H. (1952). Portfolio selection. The Journal of Finance, 7(1), 77–91. https://doi.org/10.1111/j.1540-6261.1952.tb01525.x
- Nakagawa, S., & Cuthill, I. C. (2007). Effect size, confidence interval and statistical significance: A practical guide for biologists. Biological Reviews, 82(4), 591–605. https://doi.org/10.1111/j.1469-185X.2007.00027.x
- Reed, G. F., Lynn, F., & Meade, B. D. (2002). Use of coefficient of variation in assessing variability of quantitative assays. Clinical and Diagnostic Laboratory Immunology, 9(6), 1235–1239. https://doi.org/10.1128/CDLI.9.6.1235-1239.2002
- Rousseeuw, P. J., & Croux, C. (1993). Alternatives to the median absolute deviation. Journal of the American Statistical Association, 88(424), 1273–1283. https://doi.org/10.1080/01621459.1993.10476408
- Wan, X., Wang, W., Liu, J., & Tong, T. (2014). Estimating the sample mean and standard deviation from the sample size, median, range and/or interquartile range. BMC Medical Research Methodology, 14, 135. https://doi.org/10.1186/1471-2288-14-135
- Weissgerber, T. L., Milic, N. M., Winham, S. J., & Garovic, V. D. (2015). Beyond bar and line graphs: Time for a new data presentation paradigm. PLOS Biology, 13(4), e1002128. https://doi.org/10.1371/journal.pbio.1002128
- Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. Technometrics, 4(3), 419–420. https://doi.org/10.1080/00401706.1962.10490022
