Python - Lambda Week: Integration by Simpson's Rule
Welcome to Python Week! This we we're going to cover calculus and the keyword lambda.
Note: All Python scripts presented this week were created using a TI-NSpire CX II CAS. As of June 2022, the lambda keyword is available on all calculators (in the United States) that have Python. If you are not sure, please check your calculator manual.
Simpson's Rule
The Simpson's Rule estimates numeric integrals by:
∫( f(x) dx, x = a to b) ≈
(b - a) /(3 * n) * (f(a) + 4 * f1 + 2 * f2 + 4 * f3 + .... + 2 * f_n-2 + 4 * f_n-1 + f(b))
n must be an even number of partitions. The more partitions, the higher the accuracy and the higher computation time.
integrallam.py: Numeric Integer
from math import *
print("The math module is imported.")
print("Integra of f(x), 6 places")
f=eval("lambda x:"+input("f(x)? "))
# input parameters
a=eval(input("lower = "))
b=eval(input("upper = "))
n=int(input("even parts: "))
# checksafe, add 1 if n is odd
if n/2-int(n/2)==0:
n=n+1
# integral calculus
s=f(a)+f(b)
w=1
# 1 to n-1
for i in range(1,n):
w=f(a+i*(b-a)/n)
s+=(2*w) if (i/2-int(i/2)==0) else (4*w)
s*=(b-a)/(3*n)
print("Integral: "+str(round(s,6)))
All original content copyright, © 2011-2022. Edward Shore. Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited. This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author.