首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >浮点精度细微差别

浮点精度细微差别
EN

Stack Overflow用户
提问于 2010-06-16 02:38:15
回答 3查看 423关注 0票数 3

我在NVIDIA的CUDA SDK示例中找到了这段代码。

代码语言:javascript
复制
void computeGold( float* reference, float* idata, const unsigned int len)
{
    reference[0] = 0;
    double total_sum = 0;
    unsigned int i;
    for( i = 1; i < len; ++i)
    {
        total_sum += idata[i-1];
        reference[i] = idata[i-1] + reference[i-1];
    }
    // Here it should be okay to use != because we have integer values
    // in a range where float can be exactly represented
    if (total_sum != reference[i-1])
        printf("Warning: exceeding single-precision accuracy.  Scan will be inaccurate.\n");
}
//(C) Nvidia Corp

谁能告诉我在什么情况下会打印警告,最重要的是,为什么。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-06-16 04:28:35

该函数在编写时考虑了一定范围的输入数据。如果未满足输入数据期望,则将打印以下警告:

代码语言:javascript
复制
#include <stdio.h>
#define COUNT_OF(x) (sizeof(x)/sizeof(0[(x)]))

void computeGold( float* reference, float* idata, const unsigned int len)
{
    double total_sum = 0;
    unsigned int i;

    reference[0] = 0;

    for( i = 1; i < len; ++i)
    {
        total_sum += idata[i-1];
        reference[i] = idata[i-1] + reference[i-1];
    }
    // Here it should be okay to use != because we have integer values
    // in a range where float can be exactly represented
    if (total_sum != reference[i-1])
        printf("Warning: exceeding single-precision accuracy.  Scan will be inaccurate.\n");
}
//(C) Nvidia Corp


float data[] = {
    1.0,
    2.0,
    3.0,
    4.0,
    5.0
};

float data2[] = {
    123456.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    999999.0,
    123456.0
};

float ref[COUNT_OF(data2)] = {0.0};

int main()
{
    computeGold( ref, data, COUNT_OF(data));
    computeGold( ref, data2, COUNT_OF(data2));
    return 0;
}
票数 2
EN

Stack Overflow用户

发布于 2010-06-16 02:43:05

通常,您不能对许多浮点数求和。

最终,与每个新增加的数字相比,总和变得不同的数量级,因此精度会降低。例如,在float的情况下,添加一百万个数量级相同的数字会得到与一千万相同的结果,因为当它完成时,添加的每个新数字都不会改变任何东西。

围绕这一点,有一些算法涉及对每个增加的数字进行几次乘法(实际上,只是为了对数字进行适当的求和)。是的,浮点数是很棘手的。

请参阅http://floating-point-gui.de/

票数 5
EN

Stack Overflow用户

发布于 2010-06-16 02:44:05

float的范围通常是+/- 1e38,但精度只有5到6位。这意味着,例如,可以存储类似12345678的内容,但它将仅以~6位的精度存储,因此您将收到警告。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3048043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档