在C ++中将0添加到浮点/双精度类型 [英] Adding 0 to a Float/Double Type in C++

查看:69
本文介绍了在C ++中将0添加到浮点/双精度类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说由于内部使用二进制浮点,所以像0.1 + 0.2这样的浮点运算可能会产生像0.30000000000000004这样的舍入误差.

I heard that floating point arithmetic like 0.1 + 0.2 may yield rounding error like 0.30000000000000004 due to binary floating point being used internally.

但是,如果我在C ++中的任何浮点数上添加0,是否可以保证产生相同的值而不会出现舍入错误?我不知道浮点算术如何工作以及何时出现舍入错误.

But if I add a 0 to any floating point number in C++, does it guarantee to produce the same value without any rounding error? I have no idea how floating point arithmetic works and when rounding error appears.

推荐答案

如果 C ++实现支持IEEE754数学,则可以保证.IEEE754标准具有精确的数学运算定义,因此C ++并未定义其自己的规则.但是IEEE754支持不是强制性的.

If the C++ implementation supports IEEE754 math, then it is guaranteed. The IEEE754 standard has precise definitions of mathematical operations, so C++ doesn't define its own rules. But IEEE754 support is not mandatory.

x + 0.0 == x 对于任何数字(*)都是正确的,因为IEEE754保证加法,减法,乘法和除法精确到最后一位.

x + 0.0 == x is true for any number (*) because IEEE754 guarantees that addition, subtraction, multiplication and division are precise to the last bit.

(*)当x不是数字(NaN)时, x + 0.0 也是NaN,但在IEEE754中为 NaN!= NaN .

(*) When x is Not a Number (NaN), x+0.0 is also NaN, but NaN != NaN in IEEE754.

这篇关于在C ++中将0添加到浮点/双精度类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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