การคำนวณกำลังเศษส่วน (Fractional Power) ใน C#
ใช้ Method Math.Pow(double base, double exponent) รองรับ Exponent เป็นทศนิยม (Fractional) ได้โดยตรง
ตัวอย่างพื้นฐาน
using System;
class Program
{
static void Main()
{
// 5 ยกกำลัง 3.7
double result = Math.Pow(5, 3.7);
Console.WriteLine($"Result = {result}"); // 385.646164200006
// รากที่ 2 = ยกกำลัง 0.5
double sqrt = Math.Pow(16, 0.5);
Console.WriteLine($"Sqrt(16) = {sqrt}"); // 4
// รากที่ 3 = ยกกำลัง 1/3
double cbrt = Math.Pow(27, 1.0/3.0);
Console.WriteLine($"Cbrt(27) = {cbrt}"); // 3
Console.ReadLine();
}
}
ผลลัพธ์
Result = 385.646164200006
Sqrt(16) = 4
Cbrt(27) = 3
ฟังก์ชัน Math ที่เกี่ยวข้อง
| Method | คำอธิบาย | ตัวอย่าง |
|---|---|---|
Math.Pow(x, y) | x ยกกำลัง y | Pow(2, 3) = 8 |
Math.Sqrt(x) | รากที่สอง | Sqrt(9) = 3 |
Math.Cbrt(x) | รากที่สาม (.NET Core 2.1+) | Cbrt(8) = 2 |
Math.Exp(x) | e ยกกำลัง x | Exp(1) = 2.718... |
Math.Log(x) | Natural Log (ln) | Log(Math.E) = 1 |
Math.Log10(x) | Log Base 10 | Log10(100) = 2 |
ข้อควรระวัง
- Domain Error:
Pow(negative, fractional)→ NaN (เช่นPow(-2, 0.5)= NaN) - Precision: Double มี Precision ~15-17 Digits
- Performance: Pow ช้ากว่า Multiplication ตรงๆ สำหรับ Integer Exponent
ตัวอย่างจัดการ Negative Base
double PowReal(double baseVal, double exp)
{
if (baseVal < 0 && exp % 1 != 0) // Fractional exponent with negative base
{
// Complex result - return NaN or handle specially
return double.NaN;
}
return Math.Pow(baseVal, exp);
}