simpsonrule.py

Created by vnap0v

Created on June 18, 2025

771 Bytes

The Numworks calculator can calculate definite integrals without coding using the Calculation or Grapher apps.

However this script explores the “1/3 Simpson rule” for definite integrals. It defines the function:

simpson(fun,a,b,n)
  • fun is a python function of one variable to apply integration on
  • a, b is the integration interval
  • n is the number of points to be used

The rest of the script generates a plot illustrating the function and showing the result as text.

Tested on the calculator using software version 23.2.6.


from math import *
import matplotlib.pyplot as plt
# finction to apply integration on
def sinfun(x):
  return sin(x)
# 1/3 simpson rule to calc definite integral  
def simpson(fun,a,b,n):
  h=(b-a)/n
  intg=fun(a)+fun(b)
  factor=4
  for k in range(1,n):
    x=a+(b-a)*k/n
    intg+=factor*fun(x)
    factor=4 if factor==2 else 2
  intg*=h/3
  return intg  
# calc definite integral
a=0;b=pi;n=200
intg = simpson(sinfun,a,b,n)
# preparing plot making lists for x and y
x_lst=[a+(b-a)*k/200 for k in range(1,200)]
f_lst=[sinfun(x) for x in x_lst]
plt.bar(x_lst,f_lst,0.02)
#preparing txt to add
txt="Integral from {0:.2f} to {1:.2f} = {2:.8f}".format(a,b,intg)
ytxt=min(f_lst)+(max(f_lst)-min(f_lst))*1.2
plt.text(a,ytxt,txt)
# show the plot
plt.show()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.