Floating point exceptions in c
Introduction:
During the alteration of numbers that are floating, uncommon circumstances are referred to as "floating-point exceptions" in C programming. Due to the limited accuracy of computer hardware, floating-point numbers—which are employed to represent real numbers with a fractional component—are subject to several restrictions.
Common floating-point exceptions include the following:
This exception is raised when an arithmetic operation doesn't provide a legal result, such as taking the square root for a negative integer or dividing zero by zero.
- Division by Zero: An exception occurs when attempting to multiply an integer by zero.
- Overflow: This error happens when an arithmetic operation produces a value too big to fit within the floating-point representation's available bits.
- Underflow: This error happens when the output of a calculation is too little to be represented with the floating-point representation's available bits.
- Inexact: This exception happens when there isn't enough precision to express an arithmetic operation's outcome accurately. It means the result was rounded to fit the number of bits at hand.
Using the fenv.h> header and the utilities it offers, you may regulate how these exceptions are dealt with in C. The primary methods for dealing with floating-point errors are:
- Clears the supplied floating-point exceptions using feclearexcept.
- Tests if certain floating-point exceptions have happened using the fetestexcept function.
- Raises the specified floating-point exceptions, or feraiseexcept.
- Get and modify the floating-point environment, which contains the status of floating-point exceptions, using the fegetenv and fesetenv commands.
Program:
#include <stdio.h>
#include <fenv.h>
int main() {
// Save the current floating-point environment
fenv_t env;
feholdexcept(&env);
// Perform some floating-point arithmetic operations
double result1 = 1.0 / 0.0; // Division by zero
double result2 = 1.0 + 1e308; // Overflow
// Detect exceptions
int exceptions = fetestexcept(FE_ALL_EXCEPT);
// Handle exceptions
if (exceptions & FE_DIVBYZERO) {
printf("Caught division by zero exception.\n");
}
if (exceptions & FE_OVERFLOW) {
printf("Caught overflow exception.\n");
}
// Clear exception flags
feclearexcept(FE_ALL_EXCEPT);
// Restore the original floating-point environment
fesetenv(&env);
return 0;
}
Output:
![Floating point exceptions in c](https://static.tutorialandexample.com/c/floating-point-exceptions-in-c1.png)
Types of floating point exceptions:
Operation Not Valid:
An error occurs when the arithmetic operation is tried but does not provide a correct mathematical value.
Examples include computing a non-positive number's logarithm or obtaining a negative number's square root.
It means that the operation's outcome cannot be captured within the boundaries of the floating-point numbers format.
Multiplying by zero
When attempting to multiply an integer by zero, an exception occurs.
Division by zero produces infinity or NaN (Not-a-Number) values, which are mathematically undefinable and cannot be correctly expressed in floating-point formats.
The dividing by zero exception must be handled carefully since it might result in numerical instability and strange behavior.
Overflow:
When the outcome of an arithmetic operation exceeds the range of values that the floating-point numbers format can express, overflow occurs.
For instance, combining two really large integers could produce a value larger than the format can express. Overflow can cause precision to be lost and the accuracy of future computations to be distorted.
Underflow:
Underflow occurs when the outcome of an arithmetic operation exceeds little to be precisely expressed within the range provided by the floating-point format.
Underflow occurs when a result is too near zero to be differentiated from zero in the provided format after subtracting two extremely close integers. Underflow might reduce accuracy and produce incorrect results.
Inexact:
The inexact exception arises when the restricted accuracy of the floating-point numbers format prevents an exact representation of the outcome of an arithmetic operation.
It means the outcome was rounded to fit the number of bits at hand. The limited accuracy of floating-point representations frequently results in imprecise exceptions.
Exception Handling Mechanism:
Including the header "fenv.h":
You must include the "fenv.h" header in your C program to use its exception-handling capabilities. The functions and macros in this header cover the floating-point context and exception handling.
Floating-Point Setting
The setting and flags now associated with floating-point are called the floating-point environment. Such elements as rounding mode, accuracy, and exception flags are included. The type fenv_t represents the floating-point environment.
Flagging Exceptions:
The equivalent exception flag is set if a floating-point exception happens during an arithmetic operation. The five potential flags are FE_INVALID, FE_DIVBYZERO, FE_OVERFLOW, FE_UNDERFLOW, and FE_INEXACT. The particular flags that are set depend on the type of mistake.
Exception Flag Handling:
The fetestexcept() method can determine which exception flags are active. The bitmask this method produces lists the exceptions that occurred after the flags were last cleared. It aids in determining the categories of exceptions that require handling.
Getting rid of exception flags
The provided exception flags can be cleared using the feclearexcept() method. Normally, this is carried out after identifying and handling exceptions. The environment is made ready to detect fresh exceptions by clearing the flags.
Bringing Up Exceptions
It is possible to forcibly raise certain exceptions with the feraiseexcept() method. Testing your handling of exception code by simulating a specific exception might be helpful.
Exception Trapping: Enabling and Disabling
Which exceptions are captured and which are not can be managed using the procedures feenableexcept() and fedisableexcept(). You may adjust how your program handles exceptions by turning particular exceptions on or off.
Environment Preservation and Restoration:
The full floating-point environment can be saved and restored using fegetenv() and fesetenv(). When dealing with situations where you must temporarily adjust the environment, these functions aid in maintaining consistency within the condition of the environment.