DirectX: Trouble with double values not returning a proper precision value after initializing DirectX?

After adding DirectX in a C++ project, I was experiencing an issue where double values were losing precision when being used in a math function. I was trying to figure out the issue for the past couple days, and it totally stumped me to why it was happening, such as using a formula like this:

long year = 3015;
double period =50.373180684110;
long value = long((year / double(period)) - long(year / double(period)));

The above  SHOULD return 0.373180684110, however, it was returning a incorrect value.  I looked around trying to figure out some information about values rounding off automatically/getting cut off and after a couple days of searching, I stumped over to Tom Miller’s Blog, which pointed out that DIRECTX likes to do something that alot of people seem to not realize.

When you initialize a DirectX device,  the floating point unit (FPU) is set to change to SINGLE POINT PRECISION instead of DOUBLE POINT PRECISION, which means your double values that have very long decimal points will be converted to single point precision automatically when using a math function. This means you will not get the proper value returned! What a pain! However, the reasoning for DirectX doing this is simple, they state you get a performance gain by using single instead of double precision.

Never fear though, there IS a way to keep the FPU to double point precision! You can define the flag CreateFlags.FpuPreserve when initalizing the DirectX device. On some cases, like my own, the flag is defined as #define D3DCREATE_FPU_PRESERVE 0x00000002L for simplicity when calling a device from another source file other then the DirectX source.

This should solve your issue and allow large decimals points to be used in math functions properly again! For the most case, I did not notice a performance drop at all in the 2D game myself and Brent have been working on. I would guess that it might effect 3D games that use a great deal of double values with high decimal point returns, but I’m unsure of how much this would actually be affected. I’ve checked alot of posts now about this issue, and most people do not notice any drop in performance.

So hopefully this solves issues if you are trying to figure out why your decimal points are losing precision when using math functions after you have initalized a DirectX device!

Share

Related posts:

  1. VB.NET/CSV File – How to add ‘Double quote text qualifiers’ quickly and easily!

About the Author

I mainly focus on Javascript/PHP/C++/.NET applications for everyday and work. I also am working on a remake of Stellar Frontier, an old 2D top down space battle game with a few fellow programmers.