Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Double divided by zero is returning a Divide by Zero error

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;
}
like image 924
Kynth Avatar asked Apr 19 '11 16:04

Kynth


People also ask

What type of error is a divide by zero error?

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.

Why is divide by zero an error?

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.

How do you find the divide by zero error?

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.

Why is double divided by infinity zero?

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.


1 Answers

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.

like image 150
Gabe Avatar answered Sep 18 '22 05:09

Gabe