Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import numpy as np
- DATA = [
- (37.5, 35.6),
- (35.0, 35.3),
- (31.2, 41.4),
- (38.2, 45.8),
- (55.4, 45.9),
- (30.2, 29.9),
- (24.5, 29.2),
- (31.1, 31.0),
- (42.9, 42.7),
- (34.6, 34.9),
- (31.5, 45.1),
- (34.6, 39.5),
- ]
- def fmt_comma(x, decimals=4):
- s = f"{x:.{decimals}f}"
- return s.replace(".", ",")
- def interpret_strength(r):
- ar = abs(r)
- if math.isclose(ar, 1.0, abs_tol=1e-12):
- return "Функціональний"
- if ar < 0.3:
- return "Майже відсутній"
- if ar < 0.5:
- return "Слабкий"
- if ar < 0.7:
- return "Помірний"
- return "Сильний"
- def print_strength_table():
- print("Оцінка тісноти лінійного зв'язку")
- print("Величина коефіцієнту кореляції\tХарактер зв'язку")
- print("|r| < 0,3\t\t\t\tМайже відсутній")
- print("0,3 ≤ |r| < 0,5\t\t\tСлабкий")
- print("0,5 ≤ |r| < 0,7\t\t\tПомірний")
- print("0,7 ≤ |r| < 1,0\t\t\tСильний")
- print("|r| = 1,0\t\t\t\tФункціональний")
- def main():
- decimals_table = 4
- x = np.array([p[0] for p in DATA], dtype=float)
- y = np.array([p[1] for p in DATA], dtype=float)
- n = int(len(x))
- print("=== АТЕСТАЦІЯ №1 ===")
- print("Завдання 2(9,16): коефіцієнт лінійної кореляції між удоями корів-матерів (x) і їх дочок (y)\n")
- print("--- 1) Дані (x=Мати, y=Дочка) ---")
- print(f"n = {n}\n")
- print(f"{'№':>2} {'x':>8} {'y':>8}")
- for i, (xi, yi) in enumerate(DATA, start=1):
- print(f"{i:>2} {fmt_comma(xi, 1):>8} {fmt_comma(yi, 1):>8}")
- x_mean = float(np.mean(x))
- y_mean = float(np.mean(y))
- xy = x * y
- x_dev = x - x_mean
- y_dev = y - y_mean
- x_dev2 = x_dev**2
- y_dev2 = y_dev**2
- print("\n--- 2) Розрахункова таблиця ---")
- header = (
- f"{'№':>2} {'x':>8} {'y':>8} {'xy':>10} "
- f"{'x-x̄':>10} {'y-ȳ':>10} {'(x-x̄)^2':>12} {'(y-ȳ)^2':>12}"
- )
- print(header)
- for i in range(n):
- print(
- f"{i+1:>2} "
- f"{fmt_comma(x[i], 1):>8} "
- f"{fmt_comma(y[i], 1):>8} "
- f"{fmt_comma(xy[i], decimals_table):>10} "
- f"{fmt_comma(x_dev[i], decimals_table):>10} "
- f"{fmt_comma(y_dev[i], decimals_table):>10} "
- f"{fmt_comma(x_dev2[i], decimals_table):>12} "
- f"{fmt_comma(y_dev2[i], decimals_table):>12}"
- )
- xy_mean = float(np.mean(xy))
- var_x = float(np.mean(x_dev2))
- var_y = float(np.mean(y_dev2))
- sigma_x = math.sqrt(var_x)
- sigma_y = math.sqrt(var_y)
- cov_xy = xy_mean - (x_mean * y_mean)
- denom = sigma_x * sigma_y
- print("\n--- 3) Проміжні величини ---")
- print(f"x̄ = mean(x) = {fmt_comma(x_mean, 4)}")
- print(f"ȳ = mean(y) = {fmt_comma(y_mean, 4)}")
- print(f"mean(xy) = {fmt_comma(xy_mean, 4)}")
- print(f"var_x = mean((x-x̄)^2) = {fmt_comma(var_x, 4)}")
- print(f"var_y = mean((y-ȳ)^2) = {fmt_comma(var_y, 4)}")
- print(f"σx = sqrt(var_x) = {fmt_comma(sigma_x, 4)}")
- print(f"σy = sqrt(var_y) = {fmt_comma(sigma_y, 4)}")
- print(f"cov_xy = mean(xy) - x̄*ȳ = {fmt_comma(cov_xy, 4)}")
- if math.isclose(denom, 0.0, abs_tol=1e-15):
- raise ZeroDivisionError("Неможливо обчислити r: σx*σy = 0 (нема розкиду даних).")
- r_xy = cov_xy / denom
- direction = "прямий" if r_xy > 0 else ("зворотний" if r_xy < 0 else "відсутній")
- print("\n--- 4) Коефіцієнт лінійної кореляції ---")
- print(f"r_xy = cov_xy / (σx*σy) = {fmt_comma(r_xy, 6)}")
- print(f"Напрямок зв'язку: {direction}")
- print("\n--- 5) Оцінка тісноти (таблиця) ---")
- print_strength_table()
- print(f"\nЗа отриманим r: {interpret_strength(r_xy)}")
- r_check = float(np.corrcoef(x, y)[0, 1])
- delta = abs(r_xy - r_check)
- print("\n--- 6) Контроль (numpy.corrcoef) ---")
- print(f"r_check = {fmt_comma(r_check, 6)}")
- print(f"|Δ| = {delta:.2e}")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment