สูตรดอกเบี้ยทบต้น (Compound Interest)
A = P(1 + r/n)^(nt)
- A = จำนวนเงินสุดท้าย (Future Value)
- P = เงินต้น (Principal)
- r = อัตราดอกเบี้ยต่อปี (Annual rate, decimal)
- n = จำนวนครั้งที่ทบต้นต่อปี
- t = เวลา (ปี)
โค้ดต้นฉบับใช้ n=1 (ทบต้นรายปี): A = P(1 + r)^t
ตัวอย่างโค้ด
import java.io.*;
import java.text.DecimalFormat;
public class Demo {
public static void main(String args[]) {
double principal = 456000;
double rate = 9.75 / 100; // 9.75% -> 0.0975
double time = 7; // ปี
int compoundFrequency = 1; // ทบต้นรายปี
// สูตรเต็ม: A = P(1 + r/n)^(nt)
double amount = principal * Math.pow(1 + rate / compoundFrequency, compoundFrequency * time);
double interest = amount - principal;
DecimalFormat df = new DecimalFormat("#,##0.00");
System.out.println("เงินต้น: " + df.format(principal));
System.out.println("อัตราดอกเบี้ย: " + (rate * 100) + "%");
System.out.println("ระยะเวลา: " + time + " ปี");
System.out.println("ทบต้น: " + compoundFrequency + " ครั้ง/ปี");
System.out.println("จำนวนเงินรวม (Principal + Interest): " + df.format(amount));
System.out.println("ดอกเบี้ยทบต้น: " + df.format(interest));
}
}
ผลลัพธ์
เงินต้น: 456,000.00 อัตราดอกเบี้ย: 9.75% ระยะเวลา: 7 ปี ทบต้น: 1 ครั้ง/ปี จำนวนเงินรวม (Principal + Interest): 874,573.97 ดอกเบี้ยทบต้น: 418,573.97
คำอธิบาย
โค้ดต้นฉบับคำนวณ principal * Math.pow(1 + rate/100, time) ซึ่งคือจำนวนเงินรวม (A) ไม่ใช่แค่ดอกเบี้ย (Interest)
ความถี่การทบต้น (Compounding Frequency)
| Frequency | n | ตัวอย่าง 1 ปี 10% บน 1000 |
|---|---|---|
| รายปี (Annual) | 1 | 1100.00 |
| รายครึ่งปี (Semi-annual) | 2 | 1102.50 |
| รายไตรมาส (Quarterly) | 4 | 1103.81 |
| รายเดือน (Monthly) | 12 | 1104.71 |
| รายวัน (Daily) | 365 | 1105.16 |
| ต่อเนื่อง (Continuous) | ∞ | Pe^(rt) = 1105.17 |
Continuous Compounding
// A = Pe^(rt) double continuousAmount = principal * Math.exp(rate * time);
BigDecimal สำหรับการเงิน (Precision)
import java.math.BigDecimal;
import java.math.RoundingMode;
public static BigDecimal compoundInterest(BigDecimal principal, BigDecimal rate,
int time, int frequency) {
BigDecimal one = BigDecimal.ONE;
BigDecimal n = BigDecimal.valueOf(frequency);
BigDecimal t = BigDecimal.valueOf(time);
BigDecimal base = one.add(rate.divide(n, 10, RoundingMode.HALF_UP));
BigDecimal exponent = n.multiply(t);
// BigDecimal ไม่มี pow(double) ต้องใช้ loop หรือ library
// ใช้ Apache Commons Math หรือ convert to double สำหรับ pow
return principal.multiply(...); // ต้อง implement เอง
}
การประยุกต์ใช้
- ธนาคาร สินเชื่อ บัญชีออมทรัพย์
- การลงทุน Mutual funds, Bonds
- Financial planning, Retirement calculator