首页 > 解决方案 > 在 Numpy 中对每次操作的浮点精度进行基准测试

问题描述

我想在 Numpy 中对 64 位浮点数和 32 位浮点数之间的误差进行基准测试,以进行加法和乘法运算。不幸的是,在搜索相关关键字时,我无法准确找到我正在寻找的内容。

我的直觉是,对于每个算术运算,错误都会传播和累积。

因此,我们的想法是将每次操作的误差绘制在操作次数上。对于大量操作,我希望错误会收敛到某个非零常数。相反,乘法误差收敛到零,而求和误差似乎是随机的。

import numpy as np
from matplotlib import pyplot as plt

size = 9999

test_64 = np.random.rand((size))
test_32 = test_64.astype(np.float32).astype(np.float64)

out     = np.empty((size,2))

for i in range(size):

    # summation error
    sum_64  = np.sum(test_64[:i])
    sum_32  = np.sum(test_32[:i])
    sum_er  = np.abs((sum_32) - sum_64) / (i+1)
    sum_er  = np.log(sum_er)

    # multiplication error
    mul_64  = np.prod(test_64[:i])
    mul_32  = np.prod(test_32[:i])
    mul_er  = np.abs((mul_32) - mul_64) / (i+1)
    mul_er  = np.log(mul_er)

    out[i,0] = sum_er
    out[i,1] = mul_er

x = np.linspace(1,size,size)

fig, axs = plt.subplots(2)
axs[0].plot(x,out[:,0])
axs[1].plot(x,out[:,1])

我是在错误的轨道上还是这实际上是错误的行为方式?为什么每次乘法的误差会随着每次乘法而减少?

如果我不使用内置的 Numpy 函数而是迭代数组,这会有所不同吗?

标签: pythonpython-3.xnumpyfloating-point32bit-64bit

解决方案


推荐阅读