我使用 C++ 和 Qt 创建了一些组件和辅助方法,以便在我的 QML GUI 中使用。其中一些方法计算 GUI 元素(大小、转换、场景图项创建)。目标是使用 OpenGl/Eglfs 渲染输出的 ARM 32 位。
OpenGl 使用 float
,QML 使用 real
(定义为 double
)。
我应该在 C++ 中使用什么才能不丢失任何精度?
最佳答案
如果您使用qreal
(double
),那么您不应该丢失任何精度。如果您在 qtbase.git
中 git grep float
,您可以了解更多信息:
dist/changes-5.2.0-****************************************************************************
dist/changes-5.2.0-* Important Behavior Changes *
dist/changes-5.2.0-****************************************************************************
dist/changes-5.2.0-
dist/changes-5.2.0- - Qt is now compiled with qreal typedef'ed to double on all
dist/changes-5.2.0: platforms. qreal was a float on ARM chipsets before. This guarantees more
dist/changes-5.2.0- consistent behavior between all platforms Qt supports, but is binary
dist/changes-5.2.0- incompatible to Qt 5.1 on ARM. The old behavior can be restored by
dist/changes-5.2.0: passing -qreal float to configure.
有趣的是,在 Qt 中,有大量代码已切换为仅使用 float:
commit 51d40d7e9bdfc63c5109aef5b732aa2ba10f985a
Author: Sean Harmer <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ceff9fdf2b2f4fdeef1f9eedcf7f8fdfeb2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>>
Date: Mon Aug 20 20:55:40 2012 +0100
Make gui/math3d classes use float rather than qreal
This corrects the mismatch between using floats for internal storage
and qreal in the API of QVector*D which leads to lots of implicit
casts between double and float.
This change also stops users from being surprised by the loss of
precision when using these classes on desktop platforms and removes
the need for the private constructors taking a dummy int as the final
argument.
The QMatrix4x4 and QQuaternion classes have been changed to use float
for their internal storage since these are meant to be used in
conjunction with the QVector*D classes. This is to prevent unexpected
loss of precision and to improve performance.
The on-disk format has also been changed from double to float thereby
reducing the storage required when streaming vectors and matrices. This
is potentially a large saving when working with complex 3D meshes etc.
This also has a significant performance improvement when passing
matrices to QOpenGLShaderProgram (and QGLShaderProgram) as we no
longer have to iterate and convert the data to floats. This is
an operation that could easily be needed many times per frame.
This change also opens the door for further optimisations of these
classes to be implemented by using SIMD intrinsics.
正如它所说,这是为了避免意外的精度损失,因为函数采用 qreal(double
),但将数据存储为 float
。如果您在自己的代码中到处使用 qreal
,则不会出现此问题。
另一个原因是性能。我不能对此发表太多评论,但我想说,对于 Qt 来说,针对这些事情进行优化比对于 Qt 的大多数用户来说更重要。
关于qt - 对自己的 QML 类使用 float 或 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718156/