处理浮点异常 [英] Dealing with Floating Point exceptions

查看:194
本文介绍了处理浮点异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何处理C或C ++中的浮点异常。从维基,有以下类型的浮点异常:


  IEEE 754指定了五个算术错误,将被记录在粘性位中(默认情况下,请注意,陷阱和其他替代方案是可选的,如果提供,则为非默认值)。 

*不精确,如果舍入(和返回)的值与操作的数学确切结果不同,则设置。
*下溢,如果舍入值很小(如IEEE 754中规定),则设置,并且不精确(或者可能限于如果根据IEEE 754的1984版本具有非归一化损失),返回一个次正态值(包括零)。
* overflow,如果舍入值的绝对值太大而无法表示(根据使用哪个舍入,返回无穷大或最大有限值)。
*除以零,如果结果是无限的,给定有限的操作数(返回一个无穷大,+∞或-∞),设置。
*无效,如果无法返回实值结果(如sqrt(-1)或0/0)),返回一个安静的NaN。


是否在任何类型的上述异常发生时,程序会异常退出吗?或者程序会在没有提及任何东西的情况下进行此错误,因此会使错误难以调试?



像gcc一样的编译器能够给出一些明显的例子吗?



在编码过程中我可以做些什么我的程序通知错误发生的位置,它发生什么类型,以便我可以在我的代码中轻松找到错误?请在C和C ++的情况下给出解决方案。



谢谢和恭维!

解决方案>

在Linux上,您可以使用GNU扩展程序 feenableexcept (隐藏在页面的底部)打开陷阱浮点异常 - 如果你这样做,那么你会收到信号SIGFPE当发生异常,然后你可以在调试器中捕获。注意,尽管有时,在实际导致问题的那个之后的浮点指令上抛出信号,在调试器中给出误导性的行信息!


I am not sure how to deal with floating point exceptions in either C or C++. From wiki, there are following types of floating point exceptions:

IEEE 754 specifies five arithmetic errors that are to be recorded in "sticky bits" (by default; note that trapping and other alternatives are optional and, if provided, non-default).  

* inexact, set if the rounded (and returned) value is different from the mathematically exact result of the operation.  
* underflow, set if the rounded value is tiny (as specified in IEEE 754) and inexact (or maybe limited to if it has denormalisation loss, as per the 1984 version of IEEE 754), returning a subnormal value (including the zeroes).  
* overflow, set if the absolute value of the rounded value is too large to be represented (an infinity or maximal finite value is returned, depending on which rounding is used).  
* divide-by-zero, set if the result is infinite given finite operands (returning an infinity, either +∞ or −∞).  
* invalid, set if a real-valued result cannot be returned (like for sqrt(−1), or 0/0), returning a quiet NaN.

Is it that when any type of above exceptions happens, the program will exit abnormally? Or the program will carry this error on without mentioning anything and therefore make the error hard to debug?

Is a compiler like gcc able to give warning for some obvious case?

What can I do during coding my program to notify where the error happens and what types it is when it happens, so that I can locate the error easily in my code? Please give solutions in both C and C++ case.

Thanks and regards!

解决方案

On Linux you can use the GNU extension feenableexcept (hidden right at the bottom of that page) to turn on trapping on floating point exceptions - if you do this then you'll receive the signal SIGFPE when an exception occurs which you can then catch in your debugger. Watch out though as sometimes the signal gets thrown on the floating point instruction after the one that's actually causing the problem, giving misleading line information in the debugger!

这篇关于处理浮点异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆