Để tính lũy thừa với số mũ thực (fractional/exponent), dùng Math.Pow(double base, double exponent). Trả về double.
Cú pháp
public static double Pow(double x, double y)
Tính: xy (x mũ y).
Ví dụ cơ bản
using System;
class Program
{
static void Main()
{
// 5 ^ 3.7
double result = Math.Pow(5, 3.7);
Console.WriteLine($"5 ^ 3.7 = {result}");
// Các ví dụ khác
Console.WriteLine($"2 ^ 0.5 (sqrt(2)) = {Math.Pow(2, 0.5)}");
Console.WriteLine($"8 ^ (1/3) (cbrt(8)) = {Math.Pow(8, 1.0/3)}");
Console.WriteLine($"10 ^ -2 = {Math.Pow(10, -2)}");
Console.WriteLine($"(-2) ^ 3 = {Math.Pow(-2, 3)}"); // -8 (integer exponent OK)
Console.WriteLine($"(-2) ^ 0.5 = {Math.Pow(-2, 0.5)}"); // NaN (negative base + fractional exponent)
}
}
Kết quả
5 ^ 3.7 = 385.646164200006 2 ^ 0.5 (sqrt(2)) = 1.4142135623730951 8 ^ (1/3) (cbrt(8)) = 2 10 ^ -2 = 0.01 (-2) ^ 3 = -8 (-2) ^ 0.5 = NaN
Lưu ý quan trọng
- Cơ số âm + số mũ phân số →
NaN(không xác định trong thực). Ví dụ:(-2)^0.5. - Độ chính xác:
double~15-17 chữ số. Với tài chính/khoa học chính xác cao → dùngdecimal+ thuật toán tùy chỉnh hoặc thư viện. - Hiệu năng:
Math.Powchậm hơn nhân đơn giản. Với mũ nguyên nhỏ, dùngx * x * x. - Special cases:
Pow(x, 0) = 1,Pow(0, y>0) = 0,Pow(0, y<0) = Infinity,Pow(NaN, y) = NaN.
Overload cho Decimal (Custom)
Math.Pow không có overload decimal. Cần tự triển khai hoặc dùng double rồi cast:
public static decimal Pow(decimal baseVal, decimal exponent)
{
// Chỉ dùng cho exponent nguyên hoặc chuyển double (mất precision)
if (exponent == (int)exponent)
{
decimal result = 1;
for (int i = 0; i < (int)exponent; i++) result *= baseVal;
return result;
}
return (decimal)Math.Pow((double)baseVal, (double)exponent); // Mất precision
}
Các hàm Math liên quan
| Phương thức | Mô tả |
|---|---|
Sqrt(x) | Căn bậc 2 (Pow(x, 0.5)) |
Cbrt(x) (.NET 7+) | Căn bậc 3 |
Exp(x) | ex |
Log(x) | Ln(x) (cơ số e) |
Log10(x) | Log cơ số 10 |
Log(x, base) | Log cơ số tùy chỉnh |