The nextafter functions (C99) - nextafter, nextafterf, nextafterl

実軸上で x から見て y の方向にある x の次に表現可能な値を求めます.

nextafter (C99)

#include <math.h>
double nextafter(
    double x,
    double y
);

nextafter 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,double 型で返します.

nextafterf (C99)

#include <math.h>
float nextafterf(
    float x,
    float y
);

nextafterf 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,float 型で返します.

nextafterl (C99)

#include <math.h>
long double nextafterl(
    long double x,
    long double y
);

nextafterl 関数は,実軸上で x から見て y の方向にある x の次に表現可能な値を求め,long double 型で返します.

nextafter,nextafterf,nextafterl 関数は,x がその型で表現できる最大の有限な値であり,かつその結果が無限大かその型で表現できない場合,値域エラー (range error) が発生する事があります.

よく似た関数に,nexttowardnexttowardfnexttowardl 関数があります.

戻り値

  • y の方向にある x の次の値

C言語サンプルプログラム

以下に nextafter 関数を使用したサンプルプログラムを示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* main */
int main(void) {
    double x_posi = 5.0, x_nega = -5.0;
    double y_posi = 6.0, y_nega = -6.0;
    double result;

    result = nextafter(x_posi, y_posi);
    printf("nextafter(%.1f, %.1f) = %.16f\n", x_posi, y_posi, result);

    result = nextafter(x_nega, y_posi);
    printf("nextafter(%.1f, %.1f) = %.16f\n", x_nega, y_posi, result);

    result = nextafter(x_posi, y_nega);
    printf("nextafter(%.1f, %.1f) = %.16f\n", x_posi, y_nega, result);

    result = nextafter(x_nega, y_nega);
    printf("nextafter(%.1f, %.1f) = %.16f\n", x_nega, y_nega, result);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラムの実行結果は以下のようになります.

nextafter(5.0, 6.0) = 5.0000000000000009
nextafter(-5.0, 6.0) = -4.9999999999999991
nextafter(5.0, -6.0) = 4.9999999999999991
nextafter(-5.0, -6.0) = -5.0000000000000009

Cプログラマの必読書

たくさんあるC言語関連の書籍の中でも特に役に立った本です.よかったら参考にしてみてください.

C実践プログラミング 第3版

C言語の実践的参考書.少々値段は張りますが初心者を脱しようとしている人は絶対に読むべきです.
文法だけでなく,コーディングスタイルやデバッグなど文字通り「実践的」なことが書かれているので非常にためになります. オライリーの本は,読みにくい本が多いのですが本書はとても読みやすくオススメです.


C言語ポインタ完全制覇 (標準プログラマーズライブラリ)

ポインタの解説書としては最高の書籍です.
この1冊でポインタを完全に理解することができます.全くの初学者が読むには敷居が高いですが,入門書を読み終えた後に読むと非常に有益です.