ภาพรวม
บทความนี้สาธิตวิธีบวกเศษส่วนหลายตัว และลดรูปให้เป็นรูปแบบพื้นฐาน (Simplest Form) โดยไม่แปลงเป็นทศนิยม
ตัวอย่าง
Input: [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]]
= 12/56 + 3/45 + 23/2 + 2/6 + 2/8
Output: [1731, 140] = 1731/140
การนำไปใช้
const gcd = (a, b) => {
// Euclidean Algorithm (Iterative)
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
};
const sumFrac = (a, b) => {
const [aNumer, aDenom] = a;
const [bNumer, bDenom] = b;
const resDenom = aDenom * bDenom;
const resNumer = aDenom * bNumer + bDenom * aNumer;
const g = gcd(resNumer, resDenom);
return [resNumer / g, resDenom / g];
};
const sumArrayOfFractions = (arr) =>
arr.reduce((acc, val) => sumFrac(acc, val));
console.log(sumArrayOfFractions([[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]]));
ผลลัพธ์
[1731, 140]
การปรับปรุง: ป้องกัน Overflow และ Sign Handling
const sumFractionsRobust = (fractions) => {
// fractions: [[numer, denom], ...]
let numer = 0;
let denom = 1;
for (const [n, d] of fractions) {
if (d === 0) throw new Error('Denominator cannot be zero');
// Cross multiply and add
numer = numer * d + n * denom;
denom = denom * d;
// ลดรูปทุกขั้นตอนเพื่อป้องกัน Overflow
const g = gcd(Math.abs(numer), denom);
numer /= g;
denom /= g;
}
// ให้เครื่องหมายอยู่ที่ Numerator
if (denom < 0) {
numer = -numer;
denom = -denom;
}
return [numer, denom];
};
การประยุกต์ใช้
- Exact Rational Arithmetic (ไม่สูญเสีย Precision)
- Computer Algebra Systems
- Financial Calculations: Exact Fraction Math
- Geometry: Exact Coordinate Calculations
- Signal Processing: Rational Resampling
Library แนะนำ
fraction.js- Full Fraction Librarybig.js/decimal.js- Arbitrary Precisionmathjs- Complete Math Library