Why double b=nextafter(0., 1.) is 0.000000e+00 for float type?

106 Views Asked by At

I found the result of nextafter(0., 1.) with data type double and float are not the same.

#include <math.h>
#include <stdio.h>

int main(){
    double a;
    float b;
    a=nextafter(0., 1.);
    b=nextafter(0., 1.);
    printf("default %e\n",nextafter(0., 1.));
    printf("double %e\n",a); //double 4.940656e-324
    printf("float %e\n",b); //float 0.000000e+00
    return 0;
}

Why the smallest float bigger than 0.0 is 0.000000e+00 ?

2

There are 2 best solutions below

0
NoName On BEST ANSWER

When you call nextafter(0., 1.) and store the result in a float, implicit type conversion happens. The function returns the smallest positive subnormal double, which is 4.940656 x 10⁻³²⁴. This value is then rounded to float, but it's too small to be represented as a float, leading to zero.

To get the correct float result, you should use nextafterf(0.f, 1.f):

float b = nextafterf(0.f, 1.f);

This will give you the smallest positive subnormal float.

0
wohlstad On

nextafter returns a double (a very small one in this case).
When it is converted to float to assign to b, it gets rounded to 0.

Instead you should use nextafterf, which is the float counterpart:

#include <math.h>
#include <stdio.h>

int main() {
    double a = nextafter (0., 1.);
    float  b = nextafterf(0.f, 1.f);   // <---- here
    printf("double %e\n", a);
    printf("float  %e\n", b);
    return 0;
}

Output:

double 4.940656e-324
float  1.401298e-45