C++ #define to double - 不同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21825630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
#define to double - different value?
提问by Pugz
Here are two different ways I'm defining the same value. I want it to exist as a 64-bit (double precision) float point number (aka double).
这是我定义相同值的两种不同方式。我希望它以 64 位(双精度)浮点数(又名双精度)的形式存在。
#define THISVALUE -0.148759f
double myDouble = -0.148759;
If I perform the following operation
如果我执行以下操作
double tryingIt = THISVALUE;
and I look at the value during debugging or print it, I can see it assigns tryingIt
to -0.14875899255275726
我在调试或打印过程中查看该值,我可以看到它分配tryingIt
给-0.14875899255275726
I understand that a floating point is not exact but this is just a crazy difference that really throws off my math. Directly assigning the double as in top code block gives me a value of -0.14875900000000000in the debugger - exactly what it should be.
我知道浮点数并不准确,但这只是一个疯狂的差异,真的让我无法计算。直接在顶部代码块中分配双精度值在调试器中给我一个-0.14875900000000000的值- 正是它应该是的。
Any thoughts on what's up?
有什么想法吗?
回答by unwind
You have a trailing f
in the define
:
你有一个尾随f
在define
:
#define THISVALUE -0.148759f
^
|
Which means that the literal in question is float
precision, instead of the double
default that you need. Remove that character.
这意味着所讨论的文字是float
精度,而不是double
您需要的默认值。删除那个字符。
回答by paxdiablo
Because -0.148759f
is not a double
, it's a float
. Hence it's almost certainly the differing precision which is making a difference.
因为-0.148759f
不是double
,而是float
。因此,几乎可以肯定的是,不同的精度会产生影响。
Either of these two variations should give you identical results:
这两种变化中的任何一种都应该给你相同的结果:
#define THISVALUE -0.148759
double myDouble = -0.148759; // Both double.
#define THISVALUE -0.148759f
double myDouble = -0.148759f; // Both float.
IEEE754 single precision values (commonly used in float
) have only 32 bits available to them so have limited range and precision compared to double precision values (which have 64 bits).
IEEE754 单精度值(通常用于float
)只有 32 位可用,因此与双精度值(具有 64 位)相比,其范围和精度有限。
As per the Wikipedia page on IEEE754, roughfigures for range and precision are:
根据IEEE754 上的维基百科页面,范围和精度的粗略数字是:
- For
singles
, range±10±38
with 7 digits precision. - For
doubles
, range±10±308
with 15 digits precision.
- 对于
singles
, 范围为 7 位精度。±10±38
- 对于
doubles
, 范围为 15 位精度。±10±308
And, as an aside, there's nowhere near as much reason for using macros nowadays, either for functions orobjects. The former can be done with the inline
suggestion and good compilers, the latter can be done with const int
(or const double
in your case) without losing any information between compilation stages (things like names and type information).
而且,顺便说一句,现在没有那么多理由使用宏,无论是函数还是对象。前者可以通过inline
建议和好的编译器来完成,后者可以通过const int
(或const double
在您的情况下)完成而不会在编译阶段之间丢失任何信息(例如名称和类型信息)。