簡體   English   中英

如何計算尾數位數?

[英]How to calculate number of mantissa bits?

我想計算 float 和 double 的尾數位數。 我知道這些數字應該是 23 和 52,但我必須在我的程序中計算它。

您可以使用在標題<cfloat>中定義的常量

例如,參見 FLT_MANT_DIG。

尾數位數不明確:可能是

  • 表示浮點值所需的位數。
  • 存儲到浮點表示中的位數。

通常,以 IEEE 浮點格式存儲的尾數不包括所有常規非零數所隱含的初始1 因此,表示中的位數比真實位數少一。

您可以通過不同的方式為二進制浮點格式計算此數字:

  • 一些系統定義了清單內容FLT_MANT_BITSDBL_MANT_BITSLDBL_MANT_BITS 該值是尾數位的真實數量。
  • 您可以從涉及<float.h>中定義的FLT_EPSILON的直接計算中得出位數: FLT_EPSILON是最小的浮點值,因此1.0f + FLT_EPSILON1.0f不同。 尾數的真實數量是1 - log(FLT_EPSILON) / log(2) 相同的公式可用於其他浮點格式。
  • 您可以使用循環計算值,如下面的代碼所示。

這是一個測試實用程序:

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

int main(void) {
    int n;
    float f = 1.0;
    for (n = 0; 1.0f + f != 1.0f; n++) {
        f /= 2;
    }
#ifdef FLT_MANT_BITS
    printf("#define FLT_MANT_BITS       %d\n", FLT_MANT_BITS);
#endif
#ifdef FLT_EPSILON
    printf("1 - log(FLT_EPSILON)/log(2) =  %g\n", 1 - log(FLT_EPSILON) / log(2));
#endif
    printf("Mantissa bits for float: %d\n", n);
    double d = 1.0;
    for (n = 0; 1.0 + d != 1.0; n++) {
        d /= 2;
    }
#ifdef DBL_MANT_BITS
    printf("#define DBL_MANT_BITS       %d\n", DBL_MANT_BITS);
#endif
#ifdef DBL_EPSILON
    printf("1 - log(DBL_EPSILON)/log(2) =  %g\n", 1 - log(DBL_EPSILON) / log(2));
#endif
    printf("Mantissa bits for double: %d\n", n);
    long double ld = 1.0;
    for (n = 0; 1.0 + ld != 1.0; n++) {
        ld /= 2;
    }
#ifdef LDBL_MANT_BITS
    printf("#define LDBL_MANT_BITS      %d\n", LDBL_MANT_BITS);
#endif
#ifdef LDBL_EPSILON
    printf("1 - log(LDBL_EPSILON)/log(2) = %g\n", 1 - log(LDBL_EPSILON) / log(2));
#endif
    printf("Mantissa bits for long double: %d\n", n);
    return 0;
}

我的筆記本電腦上的輸出:

1 - log(FLT_EPSILON)/log(2) =  24
Mantissa bits for float:       24
1 - log(DBL_EPSILON)/log(2) =  53
Mantissa bits for double:      53
1 - log(LDBL_EPSILON)/log(2) = 64
Mantissa bits for long double: 64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM