c# - What is causing this to behave strangely? -
i'm working in environment absent double/math library (netmf). wrote class make things easier:
public struct doubleex { public const double nan = 0.0d / 0.0d; public static bool isnan(double x) { return x != x; } ... }
seems should work, right?
well, when run code:
debug.print("method call: " + doubleex.isnan(doubleex.nan)); debug.print("method call: " + doubleex.nan != doubleex.nan);
i output:
false true
somehow, act of putting in function breaks it! there kind of optimization going on here? or hardware misinterpreting instructions?
the following based on ieee standard 754:
// @struct ieee_doublerep | allows bit access 8 byte floats //[structlayout(layoutkind.sequential)] //public struct ieee_doublerep //{ // ulong low_mantissa; // @field low 16 bits of mantissa // ushort mid_mantissa; // @field mid 16 bits of mantissa // uint high_mantissa:4; // @field high 4 bits of mantissa // uint exponent:11; // @field exponent of floating point number // uint sign:1; // @field sign of floating point number //}; public struct doubleex { public const long nanmask = 0x7ff0000000000000; public const long infinitymask = 0x000fffffffffffff; public const double nan = 0.0f / 0.0f; public const double negativeinfinity = -1.0f / 0.0f; public const double positiveinfinity = 1.0f / 0.0f; public static bool isnanbad(double x) { return x != x; } public unsafe static bool isnan(double value) { long rep = *((long*)&value); return ((rep & nanmask) == nanmask && ((rep & infinitymask) != 0)); } public unsafe static bool ispositiveinfinity(double value) { double neginf = doubleex.positiveinfinity; return *((long*)&value) == *((long*)&neginf); } public unsafe static bool isnegativeinfinity(double value) { double posinf = doubleex.positiveinfinity; return *((long*)&value) == *((long*)&posinf); } public unsafe static bool isinfinite(double x) { long rep = *((long*)&x); return ((rep & nanmask) == nanmask && ((rep & infinitymask) == 0)); } }
Comments
Post a Comment