add testing version of multiply-float.py - a wrapper that allows for float multiplication support

This commit is contained in:
dymik739 2023-05-22 22:25:34 +03:00
parent 44457b1849
commit 3598eb13f1
1 changed files with 92 additions and 0 deletions

92
src/multiply-float.py Normal file
View File

@ -0,0 +1,92 @@
# a wrapper for multiplication script which adds support for floating point numbers
from lib.prettytable import PrettyTable
from multiply import multiply, table_to_text
import bitutils as bu
def get_reference_register_size(*numbers):
return max(map(len, numbers))
def parse_float(number):
split_by_dot = number.split('.')
#print(number, split_by_dot)
Sn = split_by_dot[0] # sign
split_by_comma = split_by_dot[1].split(',')
Pn = len(split_by_comma[0].lstrip('0'))
Mn = ''.join(split_by_comma).lstrip('0')
#print(Sn, Pn, Mn)
return Sn, Pn, Mn
# compatibility layer for old multiply.py code
def to_int(number):
return int("0b" + number, 2)
def normalize_mantice(m, n):
M_norm = m.lstrip('0')
#print(m, M_norm)
P_delta = len(m) - len(M_norm)
#print(M_norm[:n], P_delta)
return M_norm[:n], P_delta
def round_mantice(m, n):
closest_upper = bu.sum(m[:n+1], '1', n+1)
return closest_upper[:n]
def print_classic_float(label, Sn, Pn, Mn):
pt = PrettyTable()
pt.field_names = [f"S{label}", f"P{label}", f"M{label}"]
pt.add_row([Sn, bin(Pn)[2:], Mn])
print(pt)
def multiply_float(x, y, method, n = 0, verbose = False):
Sx, Px, Mx = parse_float(x)
Sy, Py, My = parse_float(y)
print(f"Число X:\n" \
f"Знак мантиси: {Sx}\n" \
f"Порядок: {Px}\n" \
f"Мантиса: {Mx}\n")
print(f"Число Y:\n" \
f"Знак мантиси: {Sy}\n" \
f"Порядок: {Py}\n" \
f"Мантиса: {My}")
print("Запис чисел у класичному форматі:")
print_classic_float('x', Sx, Px, Mx)
print()
print_classic_float('y', Sy, Py, My)
print()
reg_size = get_reference_register_size(Mx, My)
table, result = multiply(n, to_int(bu.al(Mx, n)), to_int(bu.al(My, n)), method)
print(f"Процес множення другим методом:\n{table_to_text(table)}\n")
print("Маємо результат:")
S_result = bu.xor(Sx, Sy)
print(f"Знаковий розряд: {Sx} ^ {Sy} = {S_result}")
M_norm, P_delta = normalize_mantice(result, n+1)
print(f"Нормалізована мантиса: ,{M_norm}")
P_result = Px + Py - P_delta
print(f"Порядок: {Px} + {Py} - {P_delta} = {P_result}")
M_result = round_mantice(result, n)
print(f"Округлюємо мантису до {n} розрядів: ,{M_result}")
return S_result, P_result, M_result
if __name__ == "__main__":
start_x = input("X: ")
start_y = input("Y: ")
n = int(input("n: "))
method = int(input("Method: "))
S_result, P_result, M_result = multiply_float(start_x, start_y, method, n)
print(f"Запишемо результат у вигляді таблиці:")
print_classic_float('f', S_result, P_result, M_result)