C庫 - frexp() 函式



C庫函式double frexp(double x, int *exponent)返回尾數,指向**exponent**的整數是指數。結果值為**x = 尾數 * 2 ^ 指數**。

尾數是對數中小數點後的部分。

語法

以下是C庫函式frexp()的語法:

double frexp(double x, int *exponent)

引數

此函式接受兩個引數:

  • x - 這是要計算的浮點值。

  • exponent - 這是指向儲存指數值的**int**物件的指標。

返回值

此函式返回規範化分數。如果引數x不為零,則規範化分數為**x**乘以2的冪,其絕對值始終在1/2(包含)到1(不包含)的範圍內。如果**x**為零,則規範化分數為零,並且零儲存在exp中。

示例1

以下是演示frexp()函式用法的C庫程式碼。

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

int main () {
   double x = 1024, fraction;
   int e;
   
   fraction = frexp(x, &e);
   printf("x = %.2lf = %.2lf * 2^%d\n", x, fraction, e);
   
   return(0);
}

輸出

以上程式碼產生以下結果:

x = 1024.00 = 0.50 * 2^11

示例2

在此程式中,我們使用frexp()從雙精度數中提取尾數和指數。

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

int main() {
   double num = 1234.5678;
   int exponent;

   // Extract mantissa and exponent
   double mantissa = frexp(num, &exponent);

   printf("Number: %.4lf\n", num);
   printf("Mantissa: %.4lf\n", mantissa);
   printf("Exponent: %d\n", exponent);

   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Number: 1234.5678
Mantissa: 0.6028
Exponent: 11

示例3

該程式定義自定義函式my_exp(),使用尾數和指數計算e^x的近似值。

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

double my_exp(double x) {
   int exponent;
   double mantissa = frexp(x, &exponent);
   
   return ldexp(mantissa, exponent);
}

int main() {
   double x = 2.0;
   double approx_exp = my_exp(x);
   printf("Approximation of e^%.2lf = %.6lf\n", x, approx_exp);
   return 0;
}

輸出

執行程式碼後,我們得到以下結果:

Approximation of e^2.00 = 2.000000
廣告