math / modules /negative_binary.py
Sina Media Lab
Add application file 4
32f2e18
raw
history blame
1.12 kB
import random
title = "Negative Numbers in Binary"
description = "This module focuses on the binary representation of negative numbers using 2's complement and other methods."
def generate_question():
num = random.randint(-8, -1)
bit_length = 4
binary = bin((1 << bit_length) + num)[2:]
question = f"What is the binary representation of {num} using 4 bits?"
correct_answer = binary
options = [correct_answer]
# Generate incorrect options
while len(options) < 5:
fake_option = bin(random.randint(-8, -1) & 0xF)[2:]
if fake_option not in options:
options.append(fake_option)
random.shuffle(options)
explanation = (
f"The binary representation of {num} using 4 bits is {binary}."
"\n\n**Step-by-step solution:**\n"
"1. Convert the absolute value of the negative number to binary.\n"
"2. Find the 2's complement of the binary number to represent the negative number.\n"
"3. The result is the binary representation of the negative number."
)
return question, options, correct_answer, explanation