如何用张量流准确地四舍五入一半
How to accurately round half up with tensorflow
我正在尝试将一些基于C++的代码复制到Tensorflow的Python API中,但是我遇到了一些浮点不准确的问题,尽管我已经能够找到其中之一。
通常,Tensorflow 似乎以向下舍入的方式对小数进行舍入,这意味着如果我们有一个整数,其分数值正好等于0.5
,该小数的整数部分将向下舍入为零:
>>> import tensorflow as tf
>>> tf.Session().run(tf.math.round(2.5))
2.0
然而,我遇到的许多命令式编程语言都以半上舍入的方式进行舍入。其中一些编程语言是C++和Python。
事实上,考虑到Tensorflow主要是用C++,Python和Cuda C++编写的,对于他们在API中使用rounding half down
方法似乎是一个奇怪的约定。
问题:
有没有巧妙的方法来实现利用rounding half up
方法而不是rounding half down
的舍入函数?
我可以实现的最简单的函数使用tf.floormod
方法:
>>> def classical_round(x): return tf.cond(tf.math.equal(tf.floormod(x, 1), tf.constant(0.5)), lambda: tf.math.ceil(x), lambda: tf.math.round(x))
...
>>> tf.Session().run(classical_round(4.5))
5.0
>>> tf.Session().run(classical_round(4.49))
4.0
>>> tf.Session().run(classical_round(4.49999999999999))
5.0
>>> tf.Session().run(classical_round(3.2))
3.0
这是足够准确的方法吗?或者可以通过使用其他TensorFlow操作来完成类似的事情吗?
研究:
我只能找到与我的问题相关的这个 Github 问题,我认为他们最终添加了tf.math.rint
我无法在这个问题中找到位置。
谢谢!
称银行家对C#中发生的同样的事情也没有错。 你可以尝试这样的事情:
def classical_round(x):
return tf.math.floor(x+0.5)
sess.run(classical_round(2.5)) #3.0
更多信息在这里: https://en.wikipedia.org/wiki/Rounding#Round_half_to_even
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 在除法中不需要四舍五入
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何将一半传递给顶点着色器?
- 四舍五入C++
- 反转整数的一部分(一半)的函数
- 在数学上将浮点数四舍五入到 N 位小数
- 如何在C++中对OpenCV垫的小数进行四舍五入?
- 优雅和最短的方法,只保存一半的字节
- 代码占用了我输入的一半
- 向下四舍五入到五个c++的最近倍数
- 为什么屏幕上显示了一半的三角形
- DirectX11只绘制填充索引和顶点缓冲区中的一半顶点
- Systemc - 将sc_time四舍五入到最接近的第 10 SC_NS
- 如何获得 QColor::greenF 颜色值正好在 0 到 1 之间而不是四舍五入?
- 四舍五入平均值逐渐恶化
- 我的程序不断四舍五入到最接近的整数
- 为什么PNG图像的stdout有时会在printf中刷新图像的一半
- 如何用张量流准确地四舍五入一半