Quiz: Numerical methods in Python

Dr. Huidae Cho

1   Question: Numerical integration of a hard-coded polynomial function

Write Python code that calculates the integration of $f(x)=-2x^4+2x^3+2x^2-2x+0.2$ between $x=-1.2$ and $x=1$ numerically using the mid-point method (rectangular height at $x+0.5\,dx$). Use the following fact to validate your code: \[\int_{-1.2}^1 f(x)\,dx=\left.-\frac{2}{5}x^5+\frac{1}{2}x^4+\frac{2}{3}x^3-x^2+0.2x+C\,\right|_{-1.2}^1=0.7665387.\] Submit FirstLastname_numericint.py.

numerical-integration

Sample run:

n? 1000
0.7665418255703268

2   Solution

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

# define f(x) as a Python function
def f(x):
    return -2 * x**4 + 2 * x**3 + 2 * x**2 - 2 * x + 0.2

x_min = -1.2
x_max = 1

###############################
# plot f(x)
nx = 100
dnx = (x_max - x_min) / nx

xs = []
ys = []

for i in range(nx):
    x = x_min + i * dnx
    y = f(x)
    xs.append(x)
    ys.append(y)
    
_, ax = plt.subplots()
plt.plot(xs, ys, color='black')
    
###############################
# read n from the user
n = int(input("n? ")) # n is the number of rectangles
dx = (x_max - x_min) / n

integral = 0
for i in range(n):
    x = x_min + i * dx + dx / 2 # i'th x
    y = f(x)
    area = dx * y
    integral += area
    
    xy = [x - dx / 2, 0]
    width = dx
    height = y
    
    if height >= 0:
        color = 'blue'
    else:
        color = 'red'
    rect = Rectangle(xy, width, height, edgecolor='none', facecolor=color)
    ax.add_patch(rect)

print(f"solution: {integral}")

figure.png