/
ku11ch
/
Lab_3
Обзор
Документация
Войти
/
ku11ch
/
Lab_3
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
task3_1.py
97 строк
4 KB
ku11ch
upload files
14 окт 2025, 10:54
14 окт 2025, 10:54
24ce3ca
Код
Авторство
О чём код?
import random class ParityCheckCode: @staticmethod def add_parity_bit(data): ones_count = bin(data).count('1') parity_bit = 1 if ones_count % 2 != 0 else 0 return (data << 1) | parity_bit @staticmethod def check_parity(data_with_parity): data_without_parity = data_with_parity >> 1 parity_bit = data_with_parity & 1 ones_count = bin(data_without_parity).count('1') expected_parity = 1 if ones_count % 2 != 0 else 0 return parity_bit == expected_parity @staticmethod def introduce_error(data, error_position=None): if error_position is None: # Случайная позиция ошибки bits = data.bit_length() error_position = random.randint(0, bits - 1) if bits > 0 else 0 # Инвертируем бит в указанной позиции return data ^ (1 << error_position) @staticmethod def calculate_detection_probability(p, n, num_tests=10000): detected_errors = 0 total_errors = 0 for _ in range(num_tests): # Генерируем случайные данные original_data = random.randint(0, (1 << 8) - 1) encoded_data = ParityCheckCode.add_parity_bit(original_data) # Вносим ошибки согласно вероятности p corrupted_data = encoded_data error_occurred = False for i in range(n): if random.random() < p: corrupted_data ^= (1 << i) error_occurred = True if error_occurred: total_errors += 1 if not ParityCheckCode.check_parity(corrupted_data): detected_errors += 1 return detected_errors / total_errors if total_errors > 0 else 1.0 def demonstrate_parity_check(): """Демонстрация работы кода с проверкой на четность""" print("=== Код с проверкой на четность ===") # Исходные данные test_data = 0b11010101 # 213 в десятичной системе print(f"Исходные данные: {bin(test_data)} (десятичное: {test_data})") # Добавление бита четности encoded = ParityCheckCode.add_parity_bit(test_data) print(f"Данные с битом четности: {bin(encoded)}") print(f"Проверка корректности (должно быть True): {ParityCheckCode.check_parity(encoded)}") # Внесение одиночной ошибки corrupted = ParityCheckCode.introduce_error(encoded, 3) print(f"Данные с ошибкой: {bin(corrupted)}") print(f"Обнаружена ошибка: {not ParityCheckCode.check_parity(corrupted)}") # Расчет теоретического и практического коэффициента обнаружения p_error = 0.1 # Вероятность ошибки бита code_length = 9 # Длина кода (8 данных + 1 проверочный) theoretical_prob = 1 - (1 - p_error) ** code_length experimental_prob = ParityCheckCode.calculate_detection_probability(p_error, code_length, 5000) print(f"\nКоэффициент обнаружения ошибок:") print(f"Теоретический: {theoretical_prob:.4f}") print(f"Экспериментальный: {experimental_prob:.4f}") # Тестирование на различных данных print("\nТестирование на различных данных:") test_cases = [0b10101010, 0b11110011, 0b00001111, 0b01010101] for data in test_cases: encoded = ParityCheckCode.add_parity_bit(data) corrupted = ParityCheckCode.introduce_error(encoded) is_error_detected = not ParityCheckCode.check_parity(corrupted) print(f"Данные {bin(data)} -> Ошибка обнаружена: {is_error_detected}") if __name__ == "__main__": demonstrate_parity_check()