divide by zero lazarus / 13-General ---------------------------------------------------------------------- mbohn · 2009-10-13 21:54 fpc 2.2.4 Lazarus 0.9.27 OSX 10.6.1 After two full days of trying to figure out (without the help of a debugger) why my computationally-intensive Delphi app was blowing up  I found that fpc doesn't catch a divide-by-zero error.  If the offending calc is inside a try..except block the exception never gets raised.  It will report +infinity as the result if you try to print out the results but this is less than useful, especially if your Delphi code has try..except blocks all over the place. I've seen some discussion on the forum and wiki but not enough to understand why this is set up that way and if it is considered a bug. Any insight or workarounds would be appreciated. Mark ---------------------------------------------------------------------- Leledumbo · 2009-10-14 10:06 What's the type of of the expression? 1 div 0 (integer division) is indeed a EDivByZero exception, but 1 / 0 (floating point) is not. It leads to infinity as what you get. ---------------------------------------------------------------------- Bart · 2009-10-14 11:23 AFAIK an integer div by zero should raise EDivByZero, whereas a floating point division by zero should raise EZeroDivide See: http://docwiki.embarcadero.com/VCL/en/SysUtils.EZeroDivide QuoteSysUtils.EZeroDivide exception is raised when an application attempts to divide a floating-point value by zero.     Note:  Integer divide-by-zero errors raise the SysUtils.EDivByZero exception. Simple test program: Code: [Select]var r,x: extended;     i,j: integer; begin   i := 0;   r := 0.0;   try     writeln('Integer div');     j := 1 div i;     writeln('j = ',j);   except     on e: exception do writeln(e.classname,' -> ',e.message);   end;   try     writeln('Float divide');     x := 1.0 / r;     writeln('x = ',x);   except     on e: exception do writeln(e.classname,' -> ',e.message);   end; end. Output using fpc 2.2.4 (Linux i386) Code: [Select]bart@simenon:~/svnroot/lazarus> ~/LazarusProjecten/ConsoleProjecten/project1 Integer div EDivByZero -> Division by zero Float divide EDivByZero -> Division by zero So my fpc in both cases raises an EDivByZero. (or if you don't use try ..except in both cases a runtime error 200) Can anyone test with recent Delphi? Bart ---------------------------------------------------------------------- mbohn · 2009-10-14 12:43 Here is my test project.  I have a form with two edit boxes and a button.  User puts any number into edit1, clicks the button and the reciprocal of that number is put into edit2. procedure TForm1.Button1Click(Sender: TObject); var x,y:double;     s1:string; begin    x:=strtofloat(edit1.Text);    try    y:=1/x;    s1:=  floattostrf(y,ffexponent,6,2)    except     s1:='can not calc';    end;    edit2.text:=s1; end;        If edit1 contains 0.0 edit2 displays +.nf. I haven't tested it with Delphi because I've been trapping divide-by- zero errors with Delphi since V1.0 and it works. ---------------------------------------------------------------------- Marc · 2009-10-14 13:59 iirc fp detection was disabled for OSX since internally it is used, but not handled by OSX itself. This resulted in a FP exception if you hovered over a menu for instance. jonas might know more about it. ---------------------------------------------------------------------- mbohn · 2009-10-15 14:46 Marc: Should I submit this as a bug? ---------------------------------------------------------------------- Marc · 2009-10-15 23:30 iirc it is not fixable. What you can do is turn them on (set fpu mask in the Math unit) ---------------------------------------------------------------------- mbohn · 2009-10-16 13:11 Quote from: Marc on October 16, 2009, 01:30:04 amiirc it is not fixable. What you can do is turn them on (set fpu mask in the Math unit) The math unit is not used by my test program but I went through it line-by-line anyway and found no flags. With these unfixable OSX issues (divide-by-zero and the debugger) I'm beginning to have a problem with the "compile once run anywhere" concept.  Should I just install Ubuntu on my Mac? ---------------------------------------------------------------------- Bart · 2009-10-17 09:18 The fact that an floating point divide by zero raises an EDivByZero where it should raise an EZeroDivide should be considered a bug and reported then? Bart ---------------------------------------------------------------------- mbohn · 2009-10-17 12:16 Bart: What I said earlier was that it raises no exception at all. ---------------------------------------------------------------------- Bart · 2009-10-18 13:33 Quote from: mbohn on October 17, 2009, 02:16:00 pmBart: What I said earlier was that it raises no exception at all.  Yeah, I know, but that seems MAC specific. In Linux/Win it seems to raise the wrong exception. Bart ---------------------------------------------------------------------- mbohn · 2009-10-18 13:47 Yes, it is Mac specific.  So I'm wondering if I should switch to Linux.  My main app will eventually be deployed in Linux.  But I'd hate to move to Linux only to find there are fatal problems with that platform. ---------------------------------------------------------------------- Bart · 2009-10-19 08:41 You'll have to test it in Linux anyway. Write once, compile everywhere is not yet always 100% perfect. Bart ---------------------------------------------------------------------- TurboRascal · 2009-10-28 16:56 Quote from: Bart on October 17, 2009, 11:18:44 amThe fact that an floating point divide by zero raises an EDivByZero where it should raise an EZeroDivide should be considered a bug and reported then? Bart But should this be considered a bug at all? The only fault here is it doesn't closely follow Delphi behavior. Since Lazarus is declared as "not just a Delphi clone", perhaps this is a feature instead of a bug ---------------------------------------------------------------------- mbohn · 2009-10-28 17:36 Quote from: Turbo Rascal on October 28, 2009, 05:56:07 pmQuote from: Bart on October 17, 2009, 11:18:44 amThe fact that an floating point divide by zero raises an EDivByZero where it should raise an EZeroDivide should be considered a bug and reported then? Bart But should this be considered a bug at all? The only fault here is it doesn't closely follow Delphi behavior. Since Lazarus is declared as "not just a Delphi clone", perhaps this is a feature instead of a bug If it departed from Delphi for all 3 operating systems, then maybe yes.  But it seems like it departs from Delphi only for OSX. ---------------------------------------------------------------------- Troodon · 2009-10-28 17:43 Quote from: Leledumbo on October 14, 2009, 12:06:36 pmWhat's the type of of the expression? 1 div 0 (integer division) is indeed a EDivByZero exception, but 1 / 0 (floating point) is not. It leads to infinity as what you get. Hm... I don't know how to read this. Infinity is not a numerical value, so division by 0 is a mathematical impossibility. Why complicate matters? ---------------------------------------------------------------------- TurboRascal · 2009-10-29 14:09 Quote from: mbohn on October 28, 2009, 06:36:44 pmIf it departed from Delphi for all 3 operating systems, then maybe yes.  But it seems like it departs from Delphi only for OSX. But Bart showed how he also got EDivByZero for floating point division by zero in Linux... ---------------------------------------------------------------------- TurboRascal · 2009-10-29 14:12 Quote from: Troodon on October 28, 2009, 06:43:22 pmHm... I don't know how to read this. Infinity is not a numerical value, so division by 0 is a mathematical impossibility. Why complicate matters? CPU floating point units do indeed define infinity, as +Inf and -Inf IIRC. They can also return NaN. It is therefore logical that software floating point operations that use the FPU do the same. ---------------------------------------------------------------------- Troodon · 2009-10-29 14:54 Quote from: Turbo Rascal on October 29, 2009, 03:12:20 pmCPU floating point units do indeed define infinity, as +Inf and -Inf IIRC. They can also return NaN. It is therefore logical that software floating point operations that use the FPU do the same. That's funny... So, CPU makers have decided to reinvent mathematics. If one were to follow this line of reasoning then, for x = 0 (1/x = Inf) => (2/x = 2*Inf) As Inf > 0 it is "obvious" that 2*Inf > Inf How further can one push this... logic? ---------------------------------------------------------------------- TurboRascal · 2009-10-30 09:27 Apparently it's part of the IEEE 754-2008 (Standard for Floating-Point Arithmetic)... It seems they "reinvented" it to help with numerical representations in certain circumstances... Strange as it may seem, yet also the floating point format representations in FPUs don't have much connection to the "real reals" in general math ---------------------------------------------------------------------- mbohn · 2009-10-30 12:50 I've been doing some reading on the fpc mail list which seems to be a parallel discussion: http://www.mail-archive.com/fpc- pascal@lists.freepascal.org/msg17915.html They talk about a mask in the mathuh.inc file but I've yet to find that file on my system. ---------------------------------------------------------------------- Troodon · 2009-10-30 15:19 I read that post, what he wants is a division by zero "without raising an exception". That's Perl thinking. Software running without raising exceptions by default, although the results are invalid. It's a choice, I guess. ---------------------------------------------------------------------- mbohn · 2009-10-30 15:39 I can't see why you'd ever not want to raise an exception.  The IEEE discussions about some calculations that can survive a divide-by-zero error and should be allowed to proceed seems like total nonsense to me.  If I'm doing a resistor-in-parallel calculation and I know that it is possible for one of the resistances to be zero I'd prefer the computational efficiency of the exception handling heirarchy to that of testing for the possibility every time or to that of blithely letting the error propogate through the calculation. In my case it did just that and only by tediously going backwards through the calculation  sequence (without the benefit of a debugger) could I see where the problem originated.  If my try..except block had worked, I would have had zero effort. I remember when Delphi first came out and I had the hardest time understanding the concept of try..except or try..finally.  I'd be embarrassed to tell you how long it took to sink in.  When it finally did it all seemed so elegant.  Now I'm not interested in going backwards 20 years. ---------------------------------------------------------------------- Troodon · 2009-10-30 15:50 Quote from: mbohn on October 30, 2009, 04:39:37 pmI can't see why you'd ever not want to raise an exception.  The IEEE discussions about some calculations that can survive a divide-by-zero error and should be allowed to proceed seems like total nonsense to me. I totally agree with you. Not catching the result of a divide-by-zero operation as an error would entail more coding and contingency planning by the developer. ---------------------------------------------------------------------- mbohn · 2009-10-31 12:10 Quote That's funny... So, CPU makers have decided to reinvent mathematics. If one were to follow this line of reasoning then, for x = 0 (1/x = Inf) => (2/x = 2*Inf) As Inf > 0 it is "obvious" that 2*Inf > Inf How further can one push this... logic? In the case of Intel, I don't think so.  They offer both the NaN and exception-raising approaches.  This is from the Intel® 64 and IA-32 Architectures, Software Developer’s Manual Volume 1:Basic Architecture: Quote8.5  X87 FPU FLOATING-POINT EXCEPTION CONDITIONS 8.5.3  Divide-By-Zero Exception (#Z) When a divide-by-zero exception occurs and the exception is masked, the x87 FPU sets the ZE flag and returns the values shown in Table 8-10. If the divide-by-zero exception is not masked, the ZE flag is set, a software exception handler is invoked (see Section 8.7, “Handling x87 FPU Exceptions in Software”), and the top-of-stack pointer (TOP) and source operands remain unchanged. I could not get the table to look right so just go to  http://www.intel.com/Assets/PDF/manual/253665.pdf In an earlier post, Marc said that unmasking the divide-by-zero exception can result in other problems on the Mac.  I'll test that soon and report back. ---------------------------------------------------------------------- mbohn · 2009-10-31 14:44 It seems to work with my simple test program shown earlier and with the following additions: Code: [Select]implementation      uses math; . . initialization   {$I unit1.lrs}    SetExceptionMask(GetExceptionMask-[ExZeroDivide]); finalization    SetExceptionMask(GetExceptionMask+[ExZeroDivide]); end.      I haven't seen any other strange behavior but I'll report back if I do once I implement this in my real project. ---------------------------------------------------------------------- TurboRascal · 2009-11-03 09:36 Quote from: mbohn on October 31, 2009, 01:10:50 pm In the case of Intel, I don't think so.  They offer both the NaN and exception-raising approaches.  This is from the Intel® 64 and IA-32 Architectures, Software Developer’s Manual Volume 1:Basic Architecture: Oh yes, when I was talking about the IEEE standard I didn't say definitions of Inf and NaN PREVENT exceptions. Perhaps I should have remembered to say that CPU's actually DO trigger an exception when they return those values