C++ cmath nexttoward , nexttowardf and nexttowardl


The C++ <cmath> nexttoward,nexttowardf and nexttowardl function is same as the nextafter function.The declaration of the functions are given below.

1 float nexttoward(float x , long double y);
2 double nexttoward(double x , long double double y);
3 long double nexttoward(long double x , long double y);
4 float nexttowardf(float x ,long double y);
5 long double nexttowardl(long double x , long double y);

Link:C++ cmath nextafter , nextafterf and nextafterl

Parameters:
x -The first argument value.

y -The value towards which the next representable value is determine.

Return type
floating point -The next representable value.

Some points to note:

i) Like the nextafter function nexttoward determine 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.The only difference between nextafter and nexttoward is, nexttoward accept the second argument as long double type.

ii) The function return ‘y’ is ‘x’ equals ‘y’.

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

iv) 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





nexttowardf and nexttowardl

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

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

Code example

#include <typeinfo>

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

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

Output

*nexttowardf
f
f
*nexttowardl
e (means ‘long double’)
e (means ‘long double’)