简体   繁体   English

C ++:奇怪的浮点数学结果

[英]C++: Strange floating point math results

I've been struggling to find a crazy bug in some C++ code and narrowed it down to this small section. 我一直在努力寻找一些C ++代码中的疯狂错误,并将其缩小到这一小部分。 I placed into a simple main.c to debug it and can't figure out why the floating point math is rounding when it shouldn't. 我放入一个简单的main.c中进行调试,无法弄清楚为什么浮点数在不应该舍入时会四舍五入。

// setup the variables for this simple case
int writep = 672;
float offset = 672.000122;
int bufferSize = 2400;
float bufferSizeF = (float)bufferSize;

float outPointer = (float)writep - offset;       // outPointer: -0.000122070313
if(outPointer < 0.0f){
    printf("outPointer: %.9f \n", outPointer);   // outPointer: -0.000122070313
    outPointer += bufferSizeF;                   // outPointer SHOULD be: 2399.9998779296875
    printf("outpointer: %.9f \n", outPointer);   // outPointer: 2400.000000000
}

Someone...please explain. 有人...请解释。 Thanks. 谢谢。

2400.000000000 and 2399.9998779296875 are too close for a standard float to differentiate them. 2400.0000000002399.9998779296875距离标准float太近,无法区分它们。 Try this: 尝试这个:

#include<iostream>
int main() {
    std::cout << (float)2399.9998779296875 << "\n";
}

It will probably give 2400 as output. 它可能会给出2400作为输出。

An IEEE 754 single precision float can only hold about 7 to 8 significant decimal digits. IEEE 754单精度float只能容纳约7至8个有效十进制数字。 If you need a higher number of significant digits use a double precision double . 如果您需要更多的有效数字,请使用double precision double

In IEEE 754 standard the floating point numbers are not equidistantly distributed over the number axis. 在IEEE 754标准中,浮点数在数轴上不是等距分布的。 Density of floating point values is higher around 0 than around 2400, so this is why the rounding is done when value is around 2400. 浮点值的密度在0左右比2400左右高,因此这就是为什么在2400左右时进行舍入的原因。

Here is the picture to illustrate it: https://www.google.fi/search?q=IEEE+754+distribution&biw=1920&bih=895&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-tKOWkMzPAhUEDywKHRdRAEUQ_AUIBigB#imgrc=rshe5_x1ZXFoKM%3A 这是用来说明它的图片: https : //www.google.fi/search?q=IEEE+754+distribution&biw=1920&bih=895&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-tKOWkMzPAhUEDywKHRdRAEUQ_AUIBigB#imgrc=rshe5_x1ZX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM