โมดูล decimal ใน Python ใช้สำหรับคำนวณเลขทศนิยมแบบ Floating-point ที่มีความแม่นยำสูง และปัดเศษได้ถูกต้อง (Correctly-rounded) เหมาะสำหรับงานการเงิน วิทยาศาสตร์ ที่ต้องการความแม่นยำ
การใช้งาน: import decimal
1. ฟังก์ชัน Square Root (sqrt) และ Exponent (exp)
sqrt()- หารากที่สองของ Decimal objectexp()- หาค่า e^x โดย x เป็น Decimal
โค้ดตัวอย่าง
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
print('Square Root is: ' + str(my_dec.sqrt()))
print('e^x is: ' + str(my_dec.exp()))
ผลลัพธ์
25.3599999999999994315658113919198513031005859375 Square Root is: 5.035871324805668565859161094 e^x is: 103206740212.7314661465187086
2. ฟังก์ชัน Logarithmic
ln()- ลอการิทึมธรรมชาติ (ฐาน e)log10()- ลอการิทึมฐาน 10
โค้ดตัวอย่าง
import decimal
my_dec = decimal.Decimal(25.36)
print('ln(x) is: ' + str(my_dec.ln()))
print('log(x) is: ' + str(my_dec.log10()))
ผลลัพธ์
ln(x) is: 3.233173129569025152000878282 log(x) is: 1.404149249209695070459909761
3. as_tuple() และ fma() (Fused Multiply-Add)
as_tuple()- แปลง Decimal เป็น Tuple 3 ส่วน: sign, digits, exponent (sign=0 แปลว่าบวก, 1 แปลว่าลบ)fma(x, y)- คำนวณ (number * x) + y โดยส่วนคูณไม่ถูกปัดเศษกลางทาง
โค้ดตัวอย่าง
import decimal
my_dec1 = decimal.Decimal(5.3)
my_dec2 = decimal.Decimal(-9.23)
print('my_dec1 as tuple: ' + str(my_dec1.as_tuple()))
print('my_dec2 as tuple: ' + str(my_dec2.as_tuple()))
print('(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))
ผลลัพธ์
my_dec1 as tuple: DecimalTuple(sign=0, digits=(5, 2, 9...), exponent=-50) my_dec2 as tuple: DecimalTuple(sign=1, digits=(9, 2, 3...), exponent=-48) (x*5)+8 is: 34.49999999999999911182158030
4. compare() - เปรียบเทียบ Decimal
- เท่ากัน -> 0
- ตัวแรกมากกว่า -> +1
- ตัวแรกน้อยกว่า -> -1
โค้ดตัวอย่าง
import decimal print(decimal.Decimal(-5.3).compare(decimal.Decimal(-5.3))) # 0 print(decimal.Decimal(-5.3).compare(decimal.Decimal(9.26))) # -1 print(decimal.Decimal(-5.3).compare(decimal.Decimal(-13.25))) # 1
5. ฟังก์ชัน Copy ต่างๆ
copy_abs()- ค่าสัมบูรณ์copy_negate()- ค่าตรงข้าม (บวก<->ลบ)copy_sign()- คัดลอกเครื่องหมายจากอาร์กิวเมนต์ที่สอง
โค้ดตัวอย่าง
import decimal
my_dec = decimal.Decimal(-25.36)
print('Absolute:', my_dec.copy_abs())
my_dec = decimal.Decimal(7.26)
print('Negate:', my_dec.copy_negate())
my_dec = decimal.Decimal(-25.36)
print('Copy sign:', my_dec.copy_sign(decimal.Decimal(12.5)))
6. max() และ min()
หาค่าสูงสุด/ต่ำสุดระหว่างสอง Decimal
import decimal
my_dec1 = decimal.Decimal(5.3)
my_dec2 = decimal.Decimal(-9.23)
print('Minimum:', my_dec1.min(my_dec2))
print('Maximum:', my_dec2.max(my_dec1))