Return the sample variance of data. data should be an iterable of Real-valued numbers, with at least two values. The optional argument xbar, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function when your data is
(data, xbar=None)
| 518 | ## Measures of spread ###################################################### |
| 519 | |
| 520 | def variance(data, xbar=None): |
| 521 | """Return the sample variance of data. |
| 522 | |
| 523 | data should be an iterable of Real-valued numbers, with at least two |
| 524 | values. The optional argument xbar, if given, should be the mean of |
| 525 | the data. If it is missing or None, the mean is automatically calculated. |
| 526 | |
| 527 | Use this function when your data is a sample from a population. To |
| 528 | calculate the variance from the entire population, see ``pvariance``. |
| 529 | |
| 530 | Examples: |
| 531 | |
| 532 | >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] |
| 533 | >>> variance(data) |
| 534 | 1.3720238095238095 |
| 535 | |
| 536 | If you have already calculated the mean of your data, you can pass it as |
| 537 | the optional second argument ``xbar`` to avoid recalculating it: |
| 538 | |
| 539 | >>> m = mean(data) |
| 540 | >>> variance(data, m) |
| 541 | 1.3720238095238095 |
| 542 | |
| 543 | This function does not check that ``xbar`` is actually the mean of |
| 544 | ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or |
| 545 | impossible results. |
| 546 | |
| 547 | Decimals and Fractions are supported: |
| 548 | |
| 549 | >>> from decimal import Decimal as D |
| 550 | >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) |
| 551 | Decimal('31.01875') |
| 552 | |
| 553 | >>> from fractions import Fraction as F |
| 554 | >>> variance([F(1, 6), F(1, 2), F(5, 3)]) |
| 555 | Fraction(67, 108) |
| 556 | |
| 557 | """ |
| 558 | # http://mathworld.wolfram.com/SampleVariance.html |
| 559 | |
| 560 | T, ss, c, n = _ss(data, xbar) |
| 561 | if n < 2: |
| 562 | raise StatisticsError('variance requires at least two data points') |
| 563 | return _convert(ss / (n - 1), T) |
| 564 | |
| 565 | |
| 566 | def pvariance(data, mu=None): |
nothing calls this directly
no test coverage detected
searching dependent graphs…