I am experiencing an unexpected behaviour and was hoping someone could help with some guidance as to what areas to focus an investigation on.
I have two methods, one essentially performs a divide by zero test on a double, the second calls an extern
method for an unmanaged dll.
Note: In the .Net runtime, dividing a Double by Zero should return an Infinity value (amusingly of either positive or negative flavours).
Pseudocode for what I am doing looks something like this:
InfinityTest(); // Returns an Infinity value as expected
DllCall();
InfinityTest(); // Divide by zero error on second call.
The first call to InfinityTest()
returns the value Infinity as expected. The second call to InfinityTest()
throws a Divide by Zero exception that I didn't expect.
Update
The effective InfinityTest()
code below. For brevity I've removed try/catch elements, etc. I do not have permission to go into details about the DllCall()
pseudocode element, apologies.
private double InfinityTest()
{
double a = 1.0;
int b = 0;
return a / b;
}
Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed.
The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.
Examples. The following example handles a DivideByZeroException exception in integer division. using System; public class Example { public static void Main() { int number1 = 3000; int number2 = 0; try { Console. WriteLine(number1 / number2); } catch (DivideByZeroException) { Console.
In case of double/float division, the output is Infinity, the basic reason behind that it implements the floating point arithmetic algorithm which specifies a special values like “Not a number” OR “infinity” for “divided by zero cases” as per IEEE 754 standards.
Since it sounds like your DLL is changing the FP status word on you, your only choice may be to change it back. I would suggest P/Invoke to _clearfp
or _fpreset
. Here are their P/Invoke signatures:
[DllImport("msvcrt.dll")]
static extern UInt32 _clearfp();
[DllImport("msvcrt.dll")]
static extern void _fpreset();
This may not reset things back to exactly the way they were, but hopefully it will be close enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With