from numpy import nextafter,seterr
print(nextafter(0.,1.)) #5e-324
seterr(under="raise")
print(nextafter(0.,1.)) #FloatingPointError: underflow encountered in nextafter
Why is this code truggering the error below ?
FloatingPointError: underflow encountered in nextafter.
According to my tests, similar code works in C.
help(numpy.seterr) describes underflow as
Underflow: result so close to zero that some precision was lost
This corresponds to the more precise description in man feenableexcept:
The underflow exception occurs when a result has to be represented as a floating-point number, but has smaller absolute value than the smallest positive normalized floating-point number (and would lose much accuracy when represented as a denormalized number)
Zero is not a denormalized number. The next higher or lower value after zero is denormalized. Therefore a floating point exception is raised if you enable it. See also: What is a subnormal floating point number?
The following C code also signals a floating point exception:
#define _GNU_SOURCE
#include <fenv.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
double f = 0.;
feenableexcept(FE_UNDERFLOW);
f = nextafter(f, 1.);
printf("%g\n", f);
}
If you want to skip over the subnormal values, go from zero straight to numpy.finfo('f8').smallest_normal (2.2250738585072014e-308)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With