#!/usr/bin/env python3

#  -------------------------------------------------------
#   Name of project: Calculator
#   Authors: Zobal, Tajovský, Ondruška, Svoboda
#   Creation Date: 19.4.2026
#   File: stddev.py
#
#   Description: Standard deviation script using custom math library.
#
#  -------------------------------------------------------

"""
@file stddev.py
@brief Computes sample standard deviation from stdin.
@author Zobal, Tajovský, Ondruška, Svoboda
"""

import sys
from pathlib import Path
from typing import TextIO

# --- Import math library ---

# Supports both package execution and copied script execution from project root.
try:
    from lib import math_lib
except ModuleNotFoundError:
    current_dir = Path(__file__).resolve().parent
    candidate_paths = (current_dir / "src", current_dir.parent)

    for candidate_path in candidate_paths:
        if (candidate_path / "lib").is_dir():
            sys.path.insert(0, str(candidate_path))
            break

    from lib import math_lib


# --- Input stats parsing ---


def _read_stats(stream: TextIO) -> tuple[float, float, float]:
    """Parse numeric tokens from stream and return count, sum, and sum of squares."""
    n: float = 0.0
    sum_x: float = 0.0
    sum_sq_x: float = 0.0

    for line in stream:
        for token in line.split():
            try:
                x: float = float(token)

                n = math_lib.add(n, 1)
                sum_x = math_lib.add(sum_x, x)
                x_squared: float = math_lib.multiply(x, x)
                sum_sq_x = math_lib.add(sum_sq_x, x_squared)
            except ValueError:
                pass

    return n, sum_x, sum_sq_x


# --- Standard deviation computation ---


def main() -> None:
    """Read numbers from stdin and print sample standard deviation."""
    n, sum_x, sum_sq_x = _read_stats(sys.stdin)

    if n < 2:
        print("0")
        return

    mean: float = math_lib.divide(sum_x, n)

    mean_squared: float = math_lib.multiply(mean, mean)
    weighted_mean_squared: float = math_lib.multiply(n, mean_squared)
    numerator: float = math_lib.subtr(sum_sq_x, weighted_mean_squared)
    denominator: float = math_lib.subtr(n, 1)
    variance: float = math_lib.divide(numerator, denominator)

    stddev: float = math_lib.root(variance, 2)

    print(stddev)


if __name__ == "__main__":
    main()
