How would you solve below problems in C/C++?
- What is the smallest representable positive floating point number in C/C++?
- What is the largest representable negative floating point number in C/C++?
- Given a positive floating point number x, find the largest representable floating point value smaller than x?
nextafter(x, y) and nexttoward(x.y) In C and C++, both nextafter(x, y) and nexttoward(x.y) are similar functions defined in math.h or cmath header files. They both return next representable value after x in the direction of y. nexttoward() has more precise second parameter y. The following program demonstrates the concept :
CPP
// C program to demonstrate use of nextafter() and // nexttoward() #include <math.h> #include <stdio.h> int main()
{ // using nextafter
printf ( "Smallest positive floating point number : %e\n" ,
nextafter(0.0, 1.0));
printf ( "Largest negative floating point number :%e\n" ,
nextafter(0.0, -1.0));
printf ( "Largest positive floating point number smaller "
"than 0.5 : %e\n" ,
nextafter(0.5, 0.0));
// using nexttoward
printf ( "Smallest positive floating point number : %e\n" ,
nexttoward(0.0, 1.0));
printf ( "Largest negative floating point number : %e\n" ,
nexttoward(0.0, -1.0));
printf ( "Largest positive floating point number smaller "
"than 0.5 : %e\n" ,
nexttoward(0.5, 0.0));
return (0);
} |
Output
Smallest positive floating point number : 4.940656e-324 Largest negative floating point number :-4.940656e-324 Largest positive floating point number smaller than 0.5 : 5.000000e-01 Smallest positive floating point number : 4.940656e-324 Largest negative floating point number : -4.940656e-324 Largest positive floating point number smaller than 0.5 : 5.000000e-01
Time Complexity: O(1)
Auxiliary Space: O(1)