python - 在 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 函数而是迭代数组,这会有所不同吗?
解决方案
推荐阅读
- php - PHP:mysqli fetch_all 在执行时“崩溃”
- swift - 使用 IBInspectable 在 UITextField 中创建最大字符长度
- javascript - 从 package.json 加载单独的 .env
- css - Bootstrap right col right 绝对对齐到没有填充的页面
- angular - Ag 网格标题复选框选择
- c# - 如何识别泛型类型的可为空引用类型?
- python - 我在这里得到不同的最大值和最小值
- java - SoundPool 不播放声音
- java - 如何编写 C 或 Java 应用程序来处理 TCP SYN 请求
- ffmpeg - 如何使用FFmpeg android修剪带有seekbar的开始和结束位置的视频?