Can something in C# change float comparison behaviour at runtime? [x64]

前端 未结 3 1695
暗喜
暗喜 2021-02-05 04:21

I am experiencing a very weird problem with our test code in a commercial product under Windows 7 64 bit with VS 2012 .net 4.5 compiled as 64 bit.

The following test cod

相关标签:
3条回答
  • 2021-02-05 05:11

    If you're getting differences between when you debug and when it runs in release mode, you may be falling foul of the following:

    (From MS Partition I, 12.1.3):

    Storage locations for floating-point numbers (statics, array elements, and fields of classes) are of fixed size ... Everywhere else (on the evaluation stack, as arguments, as return types, and as local variables) floating-point numbers are represented using an internal floating-point type. ... its value can be represented internally with additional range and/or precision

    and,

    When a floating-point value whose internal representation has greater range and/or precision than its nominal type is put in a storage location, it is automatically coerced to the type of the storage location. This can involve a loss of precision or the creation of an out-of-range value

    and the final note:

    [Note: The use of an internal representation that is wider than float32 or float64 can cause differences in computational results when a developer makes seemingly unrelated modifications to their code, the result of which can be that a value is spilled from the internal representation (e.g., in a register) to a location on the stack. end note]

    Debugging typically causes a lot of modifications - you tend to use different optimizations and you're more likely to cause such spills.

    0 讨论(0)
  • 2021-02-05 05:18

    DirectX is known to modify the FPU settings. See this related question: Can floating-point precision be thread-dependent?

    You can either tell DirectX to preserve the FPU settings by specifying the D3DCREATE_FPU_PRESERVE flag when calling CreateDevice or execute your floating point code on a new thread.

    0 讨论(0)
  • 2021-02-05 05:24

    When I create a test application containing your test, the exception is not thrown. This means it's not going to be straightforward. Some ideas to further investigate:

    • If you run this test at the start of your application (e.g. in the Main/entry routine) does it fail then?
    • If the above is true, start a new project using the same target framework & architecture which runs the same test. If it passes, start adding in bits of your primary application gradually and see if you can find which bit makes it fail.
    0 讨论(0)
提交回复
热议问题