math / modules /number_system /twos_complement.py
Sina Media Lab
Updates
5f6edac
raw
history blame
2.31 kB
# modules/number_system/twos_complement.py
import random
import sympy as sp
title = "2's Complement Questions"
description = "This module explains the 2's complement method for representing negative numbers."
def generate_question():
bit_lengths = [4, 5, 6, 7, 8]
num_bits = random.choice(bit_lengths)
def generate_binary_number(length):
return ''.join(random.choice('01') for _ in range(length))
number = generate_binary_number(num_bits)
def calculate_twos_complement(binary_str, length):
if binary_str == '0' * length:
return binary_str # 2's complement of 0 is still 0
# Invert the bits (1's complement)
ones_complement = ''.join('1' if bit == '0' else '0' for bit in binary_str)
# Add 1 to the 1's complement
twos_complement = bin(int(ones_complement, 2) + 1)[2:]
# Ensure the result is truncated or zero-padded to fit the specified bit length
return twos_complement.zfill(length)[-length:]
correct_answer = calculate_twos_complement(number, num_bits)
options = {correct_answer}
# Generate incorrect answers
while len(options) < 4:
invalid_number = generate_binary_number(num_bits)
invalid_twos_complement = calculate_twos_complement(invalid_number, num_bits)
if invalid_twos_complement != correct_answer:
options.add(invalid_twos_complement)
options = list(options)
random.shuffle(options)
question = f"What is the 2's complement of the {num_bits}-bit binary number {number}?"
explanation = f"The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}."
step_by_step_solution = [
f"Step 1: Invert the bits (1's complement) of the binary number {number}.",
f"Step 2: Add 1 to the result to get the 2's complement.",
f"Step 3: Ensure the result is a {num_bits}-bit binary number by truncating or zero-padding if necessary.",
f"Step 4: The 2's complement of the {num_bits}-bit binary number {number} is {correct_answer}."
]
return {
"question": question,
"options": options,
"correct_answer": correct_answer,
"explanation": explanation,
"step_by_step_solution": step_by_step_solution
}