数据表示 | Data Representation

整数的表示和运算方式 | Integer Representation and Arithmetic

表示方式 | Representation

二进制 | Binary

整数在计算机中以二进制表示,每个位只包含 0 或 1。

Integers are represented in computers using binary, where each bit can be either 0 or 1.

例如:10 进制的 10 在二进制中表示为 1010

For example: Decimal 10 is represented as 1010 in binary.

补码 | Two’s Complement

补码用于表示有符号整数,最高位表示符号位,0 表示正数,1 表示负数。

Two’s complement is used to represent signed integers, where the most significant bit represents the sign, 0 for positive and 1 for negative.

例如:8 位的-5 在补码中表示为 11111011

For example: -5 in 8-bit two’s complement is represented as 11111011.

运算方式 | Arithmetic

加法 | Addition

将两个二进制数相加,处理进位。

Add two binary numbers and handle the carry.

# Example in Python
a = 0b1010  # 10 in decimal
b = 0b0110  # 6 in decimal
result = a + b  # 0b10000, which is 16 in decimal
print(bin(result))  # Output: 0b10000

减法 | Subtraction

将被减数加上减数的补码。

Subtract by adding the minuend to the two’s complement of the subtrahend.

# Example in Python
a = 0b1010  # 10 in decimal
b = 0b0011  # 3 in decimal
result = a + (~b + 1)  # 0b0111, which is 7 in decimal
print(bin(result))  # Output: 0b111

乘法和除法 | Multiplication and Division

通过移位和加法/减法实现。

Implemented via shifts and additions/subtractions.

# Example of multiplication in Python
a = 0b101  # 5 in decimal
b = 0b11   # 3 in decimal
result = a * b  # 0b1111, which is 15 in decimal
print(bin(result))  # Output: 0b1111

浮点数的表示和运算方式 | Floating Point Representation and Arithmetic

表示方式 | Representation

IEEE 754 标准 | IEEE 754 Standard

浮点数使用 IEEE 754 标准表示,包含三个部分:符号位、指数位和尾数位。

Floating-point numbers are represented using the IEEE 754 standard, consisting of three parts: sign bit, exponent, and mantissa.

例如:32 位浮点数

For example: 32-bit floating point number

符号位 | Sign Bit: 1 位 (bit)
指数位 | Exponent: 8 位 (bits)
尾数位 | Mantissa: 23 位 (bits)

规格化 | Normalization

浮点数表示为

Floating-point numbers are represented as

运算方式 | Arithmetic

加法和减法 | Addition and Subtraction

对齐指数后相加或相减。

Align exponents and then add or subtract.

# Example in Python
import numpy as np
a = np.float32(1.5)
b = np.float32(2.25)
result = a + b  # 3.75 in decimal
print(result)  # Output: 3.75

乘法和除法 | Multiplication and Division

分别乘或除尾数,并加或减指数。

Multiply or divide mantissas and add or subtract exponents.

# Example of multiplication in Python
a = np.float32(1.5)
b = np.float32(2.0)
result = a * b  # 3.0 in decimal
print(result)  # Output: 3.0

精度问题 | Precision Issues

浮点数运算可能产生精度误差,特别是累加和大数相减。

Floating-point arithmetic can introduce precision errors, especially in summation and subtraction of large numbers.

# Precision issue example
a = np.float32(1e10)
b = np.float32(1)
result = a + b - a  # Expected: 1, Actual: 0
print(result)  # Output: 0.0