本文翻译自:What does the constant 0.0039215689 represent?
I keep seeing this constant pop up in various graphics header files 我一直看到这个常量弹出各种图形头文件
0.0039215689
It seems to have something to do with color maybe? 它似乎与颜色有关吗?
Here is the first hit on Google : 这是Google的第一个热门话题 :
void RDP_G_SETFOGCOLOR(void)
{
Gfx.FogColor.R = _SHIFTR(w1, 24, 8) * 0.0039215689f;
Gfx.FogColor.G = _SHIFTR(w1, 16, 8) * 0.0039215689f;
Gfx.FogColor.B = _SHIFTR(w1, 8, 8) * 0.0039215689f;
Gfx.FogColor.A = _SHIFTR(w1, 0, 8) * 0.0039215689f;
}
void RDP_G_SETBLENDCOLOR(void)
{
Gfx.BlendColor.R = _SHIFTR(w1, 24, 8) * 0.0039215689f;
Gfx.BlendColor.G = _SHIFTR(w1, 16, 8) * 0.0039215689f;
Gfx.BlendColor.B = _SHIFTR(w1, 8, 8) * 0.0039215689f;
Gfx.BlendColor.A = _SHIFTR(w1, 0, 8) * 0.0039215689f;
if(OpenGL.Ext_FragmentProgram && (System.Options & BRDP_COMBINER)) {
glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, Gfx.BlendColor.R, Gfx.BlendColor.G, Gfx.BlendColor.B, Gfx.BlendColor.A);
}
}
//...more like this
What does this number represent? 这个数字代表什么? Why does no one seem to declare it as a const? 为什么似乎没有人将它声明为const?
I couldn't find anything on Google that explained it. 我无法在Google上找到解释它的任何内容。
参考:https://stackoom.com/question/1Wuoj/常数-代表什么
This multiplication by 0.0039215689f
converts an integer valued color intensity in the range 0 to 255 to a real valued color intensity in the range 0 to 1. 乘以0.0039215689f
将0到255范围内的整数值颜色强度转换为0到1范围内的实值颜色强度。
As Ilmari Karonen points out, even if this is an optimisation it's a rather badly expressed one. 正如Ilmari Karonen指出的那样,即使这是一个优化,它也是一个相当糟糕的表达。 It would be so much clearer to multiply by (1.0f/255)
. 乘以(1.0f/255)
会更加清晰。
0.0039215689
is approximately equal to 1/255
. 0.0039215689
约等于1/255
。
Seeing that this is OpenGL, performance is probably important. 看到这是OpenGL,性能可能很重要。 So it's probably safe to guess that this was done for performance reasons. 所以可以安全地猜测这是出于性能原因而做的。
Multiplying by the reciprocal is faster than repeatedly dividing by 255. 乘以倒数比重复除以255要快。
Side Note: 边注:
If you're wondering why such a micro-optimization isn't left to the compiler, it's because it is an unsafe floating-point optimization. 如果你想知道为什么这样的微优化不会留给编译器,那是因为它是一个不安全的浮点优化。 In other words: 换一种说法:
x / 255 != x * (1. / 255)
due to floating-point round-off errors. 由于浮点舍入错误。
So while modern compilers may be smart enough to do this optimization, they are not allowed to do it unless you explicitly tell them to via a compiler flag. 因此,虽然现代编译器可能足够聪明以进行此优化,但除非您通过编译器标志明确告诉它们,否则不允许它们执行此操作。
Related: Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? 相关: 为什么GCC没有优化a * a * a * a * a * a到(a * a * a)*(a * a * a)?