# Bitwise multiplication using Russian Peasant Multiplication.
def bitwise_multiply(a, b):
result = 0
while b:
if b & 1:
result += a
a <<= 1
b >>= 1
return result
# Bitwise matrix-vector multiplication.
def bitwise_matrix_vector_mult(A, x):
n = len(A)
result = [0] * n
for i in range(n):
for j in range(len(x)):
result[i] += bitwise_multiply(A[i][j], x[j])
return result
# Bitwise matrix scaling (using shifts if c is a power of 2).
def bitwise_scale_matrix(A, c):
# Check if c is a power of 2.
if c != 0 and (c & (c - 1)) == 0:
shift = c.bit_length() - 1
return [[entry << shift for entry in row] for row in A]
else:
return [[bitwise_multiply(entry, c) for entry in row] for row in A]
# Bitwise Jacobian: For scale-invariant functions, returns A unchanged.
def bitwise_jacobian(A, x):
return A
# Bitwise Hessian singularity check: For 1-homogeneous functions, returns a zero vector.
def bitwise_hessian_is_singular(A, x):
return [0] * len(x)
# Bitwise pseudo-quadratic energy calculation.
def bitwise_pseudo_quadratic_energy(A, x):
n = len(x)
sum_energy = 0
for i in range(n):
for j in range(n):
sum_energy += bitwise_multiply(x[i], A[i][j]) * x[j]
return sum_energy >> 1 # Right shift by 1 is equivalent to integer division by 2.
# Example data.
A = [[1, 2], [3, 4]] # Example matrix.
x = [5, 6] # Example vector.
c = 2 # Scale factor.
# Build tensor-like structure (as a nested dictionary).
tensor_structure = {
"Function Calls": {
"Bitwise Matrix-Vector Multiplication": bitwise_matrix_vector_mult(A, x),
"Bitwise Matrix Scaling": bitwise_scale_matrix(A, c),
"Bitwise Jacobian": bitwise_jacobian(A, x),
"Bitwise Hessian Singularity": bitwise_hessian_is_singular(A, x),
"Pseudo-Quadratic Energy": bitwise_pseudo_quadratic_energy(A, x)
},
"Matrix Inputs": A,
"Vector Inputs": x,
"Tracked Optimizations": {
"Bitwise Multiplications Count": sum(1 for row in A for entry in row if entry != 0),
"Bitwise Shifts Count": sum(1 for row in A for entry in row if entry != 0 and (entry & (entry - 1)) == 0)
}
}
# Function to nicely print the tensor structure.
def print_tensor_structure(tensor, indent=0):
spacing = " " * indent
if isinstance(tensor, dict):
for key, value in tensor.items():
print(f"{spacing}{key}:")
print_tensor_structure(value, indent + 1)
elif isinstance(tensor, list):
print(f"{spacing}{tensor}")
else:
print(f"{spacing}{tensor}")
# Print out the complete tensor structure.
print("Bitwise Computation Tensor Structure:")
print_tensor_structure(tensor_structure)