std::isnormal (header <cmath>, C++11) kiểm tra xem một giá trị floating-point có phải là số bình thường (normal number) hay không.
Phân loại Floating-point (IEEE 754)
| Phân loại | Mô tả | isnormal() |
| Zero (±0.0) | Giá trị 0 | false |
| Subnormal (denormal) | Gần 0, độ chính xác giảm | false |
| Normal | Số thực tiêu chuẩn, có leading bit 1 | true |
| Infinity (±inf) | Vô cùng | false |
| NaN | Not a Number | false |
Cú pháp
bool isnormal(float x);
bool isnormal(double x);
bool isnormal(long double x);
Ví dụ kiểm tra các trường hợp
#include <bits/stdc++.h>
using namespace std;
void test_type(const char* name, auto val) {
cout << name << ": isnormal = " << isnormal(val) << '\n';
}
int main() {
cout << "=== Float ===\n";
test_type("5.89f", 5.89f);
test_type("0.0f", 0.0f);
test_type("2.2f/0.0f (inf)", 2.2f/0.0f);
test_type("0.0f/0.0f (NaN)", 0.0f/0.0f);
test_type("1e-40f (subnormal)", 1e-40f); // Phụ thuộc platform
cout << "\n=== Double ===\n";
test_type("5.89", 5.89);
test_type("0.0", 0.0);
test_type("2.2/0.0 (inf)", 2.2/0.0);
test_type("0.0/0.0 (NaN)", 0.0/0.0);
test_type("1e-320 (subnormal)", 1e-320);
cout << "\n=== Long Double ===\n";
test_type("5.89L", 5.89L);
test_type("0.0L", 0.0L);
test_type("2.2L/0.0L (inf)", 2.2L/0.0L);
test_type("0.0L/0.0L (NaN)", 0.0L/0.0L);
return 0;
}
Đầu ra (điển hình)
=== Float ===
5.89f: isnormal = 1
0.0f: isnormal = 0
2.2f/0.0f (inf): isnormal = 0
0.0f/0.0f (NaN): isnormal = 0
1e-40f (subnormal): isnormal = 0
=== Double ===
5.89: isnormal = 1
0.0: isnormal = 0
2.2/0.0 (inf): isnormal = 0
0.0/0.0 (NaN): isnormal = 0
1e-320 (subnormal): isnormal = 0
=== Long Double ===
5.89L: isnormal = 1
0.0L: isnormal = 0
2.2L/0.0L (inf): isnormal = 0
0.0L/0.0L (NaN): isnormal = 0
Hàm phân loại liên quan (C++11)
| Hàm | Kiểm tra |
fpclassify(x) | Trả về enum: FP_NORMAL, FP_ZERO, FP_SUBNORMAL, FP_INFINITE, FP_NAN |
isfinite(x) | Không phải inf/NaN (normal + subnormal + zero) |
isinf(x) | Là ±infinity |
isnan(x) | Là NaN |
isnormal(x) | Là normal (không zero, subnormal, inf, NaN) |
signbit(x) | Bit dấu (1 = âm) |
Ứng dụng
- Kiểm tra hợp lệ trước khi tính toán (tránh subnormal chậm, inf/NaN lan truyền).
- Validation input dữ liệu khoa học.
- Debug numerical instability.
Lưu ý
- C++11 trở lên. C cũ dùng
isnormal() từ <math.h> (macro/function-like).
- Subnormal numbers (denormal) là số có exponent nhỏ nhất nhưng leading bit = 0, cho phép biểu diễn giá trị gần 0 hơn nhưng chậm hơn trên một số CPU.