xref: /petsc/src/sys/tests/ex59.c (revision bd2b07b136135af06fb9210476dad9bf59a36938)
1*bd2b07b1SBarry Smith 
2*bd2b07b1SBarry Smith static char help[] = "Tests not trapping an underflow\n\n";
3*bd2b07b1SBarry Smith 
4*bd2b07b1SBarry Smith #include <petscsys.h>
5*bd2b07b1SBarry Smith #include <float.h>
6*bd2b07b1SBarry Smith #include <math.h>
7*bd2b07b1SBarry Smith 
8*bd2b07b1SBarry Smith /* From https://stackoverflow.com/questions/37193363/float-underflow-in-c-explanation */
9*bd2b07b1SBarry Smith void demo(void) {
10*bd2b07b1SBarry Smith   /*
11*bd2b07b1SBarry Smith   FLT_MIN, FLT_MIN and the display of the floating point numbers are not portable
12*bd2b07b1SBarry Smith 
13*bd2b07b1SBarry Smith   const char *format = "%.10e %a\n";
14*bd2b07b1SBarry Smith   printf(format, FLT_MIN, FLT_MIN);
15*bd2b07b1SBarry Smith   printf(format, FLT_TRUE_MIN, FLT_TRUE_MIN);
16*bd2b07b1SBarry Smith   */
17*bd2b07b1SBarry Smith 
18*bd2b07b1SBarry Smith   float f = nextafterf(1.0f, 2.0f);
19*bd2b07b1SBarry Smith   do {
20*bd2b07b1SBarry Smith     /* if trapping of underflow is turned on then this will generate an exception */
21*bd2b07b1SBarry Smith     f /= 2;
22*bd2b07b1SBarry Smith     /* printf(format, f, f); */
23*bd2b07b1SBarry Smith   } while (f);
24*bd2b07b1SBarry Smith }
25*bd2b07b1SBarry Smith 
26*bd2b07b1SBarry Smith int main(int argc, char **argv) {
27*bd2b07b1SBarry Smith   PetscFunctionBeginUser;
28*bd2b07b1SBarry Smith   PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
29*bd2b07b1SBarry Smith   demo();
30*bd2b07b1SBarry Smith   PetscCall(PetscFinalize());
31*bd2b07b1SBarry Smith   return 0;
32*bd2b07b1SBarry Smith }
33*bd2b07b1SBarry Smith 
34*bd2b07b1SBarry Smith /*TEST
35*bd2b07b1SBarry Smith 
36*bd2b07b1SBarry Smith    test:
37*bd2b07b1SBarry Smith      TODO: Doesn't work on AArch64 targets. There's a known hardware limitation. arch-ci-linux-cmplx-single
38*bd2b07b1SBarry Smith      args: -fp_trap
39*bd2b07b1SBarry Smith 
40*bd2b07b1SBarry Smith TEST*/
41