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

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

问题描述

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


  IEEE 754指定五种算术运算错误要被记录在粘比特(默认;请注意,俘获和其他替代是可选的,并且如果提供的,非缺省值)。*不精确,如果设置了圆形的(和返回)值是从操作的数学精确结果的不同。
*下溢,设置如果舍入值很小(如IEEE 754指定)和不精确(或者仅限于它是否有denormalisation损失,按1984年版的IEEE 754),返回低于正常值(包括零)。
*溢出,如果舍入值的绝对值太大,重新presented(无穷大或最大有限值返回,具体取决于使用四舍五入)设置。
*除以零,如果结果是无限的给予有限的操作数(返回无穷大,无论是+∞或-∞)。
*无效的,如果设置一个实值计算结果不能退换(像开方(-1),或0/0),返回静态NaN。


难道当任何类型的上述异常发生时,程序会异常退出?否则程序将携带这种错误在没有任何提及,因此使错误难以调试?

仿佛是GCC能够给予警告,对一些明显的情况下,编译器?

编码我的程序,通知那里的错误发生,它发生时,它是什么类型的,这样我可以在我的code容易查找错误时我能做些什么?请给在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天全站免登陆