大浮点数的OpenCL减少结果错误 [英] OpenCL reduction result wrong with large floats

查看:88
本文介绍了大浮点数的OpenCL减少结果错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 AMD的两级约简示例,使用浮点精度计算从0到65 536的所有数字的和.不幸的是,结果不正确.但是,当我修改代码以计算65 536个较小数字的总和(例如1)时,结果是正确的.

I used AMD's two-stage reduction example to compute the sum of all numbers from 0 to 65 536 using floating point precision. Unfortunately, the result is not correct. However, when I modify my code, so that I compute the sum of 65 536 smaller numbers (for example 1), the result is correct.

我在代码中找不到任何错误.由于float类型,我是否有可能得到错误的结果?如果是这样,解决问题的最佳方法是什么?

I couldn't find any error in the code. Is it possible that I am getting wrong results, because of the float type? If this is the case, what is the best approach to solve the issue?

推荐答案

内核或主机应用程序的编码中可能没有错误.问题在于单精度浮点数.

There is probably no error in the coding of your kernel or host application. The issue is with the single-precision floating point.

正确的总和是:65537 * 32768 = 2147516416,它需要31位才能用二进制表示(10000000000000001000000000000000). 32位浮点数只能精确地存储整数,最大为2 ^ 24.

The correct sum is: 65537 * 32768 = 2147516416, and it takes 31 bits to represent it in binary (10000000000000001000000000000000). 32-bit floats can only hold integers accurately up to 2^24.

任何绝对值小于[2 ^ 24]的整数都可以用单精度格式精确表示" 浮点"文章,维基百科

"Any integer with absolute value less than [2^24] can be exactly represented in the single precision format" "Floating Point" article, wikipedia

这就是为什么当小于或等于2 ^ 24时获得正确的和的原因.如果使用单精度进行完整的求和,则无论您在哪个设备上执行内核,最终都会失去精度.您可以采取一些措施来获得正确的答案:

This is why you are getting the correct sum when it is less than or equal to 2^24. If you are doing a complete sum using single-precision, you will eventually lose accuracy no matter which device you are executing the kernel on. There are a few things you can do to get the correct answer:

  • 如果您的平台支持,请使用double而不是float
  • 使用int或unsigned int
  • 求和一组较小的数字,例如:0 + 1 + 2 + ... + 4095 + 4096 =(2 ^ 23 + 2 ^ 11)

在此处详细了解单精度.

这篇关于大浮点数的OpenCL减少结果错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆