เมื่อต้องการคำนวณค่าคงที่ออยเลอร์ e ใช้สูตรอนุกรม: e = 1 + 1/1! + 1/2! + ... + 1/n!
ตัวอย่างโค้ด
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def compute_e(n):
s = 1.0 # เริ่มจาก 1 (พจน์แรก)
for i in range(1, n + 1):
s += 1.0 / factorial(i)
return s
value = 5
print("The value is:", value)
print("The result is:", compute_e(value))ผลลัพธ์
The value is: 5 The result is: 2.7166666666666663
คำอธิบาย
ฟังก์ชัน
factorialคำนวณแฟกทอเรียลแบบทวนลำดับฟังก์ชัน
compute_eรวมผลรวมของ 1/i! สำหรับ i = 1 ถึง nเริ่มต้นผลรวมที่ 1.0 (พจน์ 1/0!)
ยิ่ง n มาก ยิ่งค่าประมาณการใกล้ค่า e จริง (~2.71828)