截断三进制乘法器ulp误差计算
对于截断三进制乘法器,它的误差是由舍入引起的。而这种误差可以通过计算ulp(unit in the last place)来衡量。对于一个给定的截断位数,我们可以计算出一组可能的输入值,然后计算它们在乘法器中的误差,并以ulp为单位进行表示。
下面是一个示例代码,用于计算6位二进制数的截断三进制乘法器的ulp误差:
import numpy as np
def truncated_ternary_multiplier(x, y):
b = 3 # base of the number system
n = 6 # number of bits
# convert binary inputs to ternary form
x_tern = np.zeros(n, dtype=np.int8)
y_tern = np.zeros(n, dtype=np.int8)
for i in range(n):
x_tern[i] = x[i]*2 - x[i-1]
y_tern[i] = y[i]*2 - y[i-1]
# compute partial products
p = np.zeros((2*n-1, n), dtype=np.int8)
for i in range(n):
for j in range(n):
s = x_tern[i]*y_tern[j]
p[i+j,i] = s//b
p[i+j+1,i] = s%b
# compute partial sums
c = np.zeros(n, dtype=np.int8)
for i in range(2*n-1):
c += p[i,:]
c = np.concatenate(([0], c[:-1]))
# convert result to binary form
z = np.zeros(n, dtype=np.int8)
for i in range(n):
if c[i] == 1:
z[i] = 1
elif c[i] == -1:
z[i] = 0
c[i+1] -= 1
return z
# compute ulp error for truncated ternary multiplier
def compute_ulp_error(n):
eps = np.finfo(float).eps # machine epsilon
x = np.random.randint(2, size=n)
y = np.random.randint(2, size=n)
z = truncated_ternary_multiplier(x, y)
z_float = np.packbits(z)
z_float /= np.power(2.0, np.arange(n)[::-1])
x_float = np.packbits(x) / np.power(2.0, np.arange(n)[::-1])
y_float = np.packbits(y) / np.power(2.0, np.arange(n)[::-1])
true_z_float = x_float * y_float
error = true_z_float - z_float
ulp_error = error / eps
max_ulp_error = np.max(np.abs(ulp_error))
return max_ulp_error
# compute maximum ulp error over a set of trials
num_trials = 1000
max_ulp_error = 0
for i in range(num_trials):
error = compute_ulp_error(6)
if error > max_ulp_error:
max_ulp_error = error
print("Maximum ulp error over {} trials: {}".format(num_trials, max_ulp_error))
注意,在本代码示例中,我们使用的是numpy库的函数来实现各种数学运算。同时,对于