C++ cmath nextafter , nextafterf and nextafterl


1 float nextafter(float x , float y);
2 double nextafter(double x , double y);
3 long double nextafter(long double x , long double y);
4 float nextafterf(float x , float y);
5 long double nextafterl(long double x , long double y);

The C++ <cmath> nextafter,nextafterf and nextafterl function return the next representable value in the type of the function after x in the direction of y,where x and y are first converted to the type of the function.

Some points to note:

i) The function return ‘y’ if ‘x’ equals ‘y’.

ii) If x is ±∞ ,a range error may occur or a largest representable value of the type may be returned.

ii) If x is NaN ,’nan’ is returned.

Code example

cout<< “nextafter(23 , 90)=” << nextafter(23 ,90) << endl ;

/*Passing x as ∞ */
cout<< “nextafter(∞ , 90)=” << nextafter(23 ,90) << endl ;

/*Passing x as NaN */
cout<< “nextafter(NaN , 90)=” << nextafter(23 ,90) << endl ;

Output

nextafter(23 , 90)= 23
nextafter(∞ , 90)= 1.79769e+308
nextafter(NaN , 90)= nan


 


nextafterf and nextafterl

i)The 4th version nextafterf is same as the 1st version float nextafter(float , float).The last character ‘f‘ in ‘nextafterf’ stands for ‘float’ which signify the argument type and return type of the function.

ii)The 5th version nextafterl is same as the 3rd version long double nextafter(long double , long double).The last character ‘l‘ in ‘nextafterl’ stands for ‘long double’ which signify the argument type and return type of the function.

Code example

#include <typeinfo>

/*nextafterf */
cout<< “*nextafterf\n”;
float f=2 , f1=99;
cout<< typeid( nextafterf(2 , 99) ).name() << endl /*identify type of nextafterf returned value */
<< typeid( nextafter(f , f1) ).name() << endl; /*identify type of nextafter(float , float) returned value */

/*nextafterl*/
cout<< “*nextafterl\n”;
long double ld=2 , ld1=89;
cout<< typeid( nextafterl(2 , 89) ).name() << endl /*identify type of nextafterl returned value */
<< typeid( nextafter(ld , ld1) ).name() << endl; /*identify type of nextafter(long double , long double) returned value*/

Output

*nextafterf
f
f
*nextafterl
e (means ‘long double’)
e (means ‘long double’)


Related links

->C programming nextafter,nextafterf and nextafterl math.h