Hàm frexp() phân tách số thực thành mantissa (độ chính xác) và exponent (số mũ) cơ số 2. Công thức: x = mantissa × 2^exponent.
Cú pháp
float frexp(float x, int* exp); double frexp(double x, int* exp); long double frexp(long double x, int* exp);
Tham số
- x - Số cần phân tách
- exp - Con trỏ lưu số mũ (exponent)
Giá trị trả về
- Mantissa trong khoảng [0.5, 1) (hoặc 0 nếu x = 0)
- Số mũ lưu qua con trỏ
exp
Ví dụ
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x = 4.0;
int exp;
double mantissa = frexp(x, &exp);
cout << "x = " << x << endl;
cout << "Mantissa = " << mantissa << endl;
cout << "Exponent = " << exp << endl;
cout << "Kiểm tra: " << mantissa << " * 2^" << exp
<< " = " << ldexp(mantissa, exp) << endl;
// Thử với số khác
cout << "\n--- Các ví dụ khác ---" << endl;
double vals[] = {0.5, 1.0, 3.14, 100.0, -8.0};
for (double v : vals) {
int e;
double m = frexp(v, &e);
cout << v << " = " << m << " * 2^" << e << endl;
}
return 0;
}
Kết quả
x = 4 Mantissa = 0.5 Exponent = 3 Kiểm tra: 0.5 * 2^3 = 4 --- Các ví dụ khác --- 0.5 = 0.5 * 2^0 1 = 0.5 * 2^1 3.14 = 0.785 * 2^2 100 = 0.78125 * 2^7 -8 = -0.5 * 2^4
Ứng dụng
- Phân tích biểu diễn floating-point (IEEE 754)
- Thuật toán số học, chuẩn hóa số
- Cặp với
ldexp()để nhân/chia lũy thừa 2 - Có từ C++11 (
<cmath>)