Demo entry 2584737



Submitted by anonymous on Aug 31, 2015 at 21:13
Language: Python. Code size: 893 Bytes.

from __future__ import division
import matplotlib.pyplot as plt
import math
import numpy as np

# helper functions:

def f(x):
    return math.sin(x)

def d3f(x):
    return -1.0*math.cos(x)

def d4f(x):
    return math.sin(x)

def d3f_approx(x, h):
    return (1/h**3)*(f(x+3*h)-3*f(x+2*h)+3*f(x+h)-f(x))

def truncation_err(x, h):
    return h*d4f(x)

# setup:
x0 = 0.7
machine_eps = np.finfo(float).eps
kvals = range(1, 16)
hvals = [2**-k for k in kvals]

# error calculation:
abs_err = [abs(d3f_approx(x0, h)-d3f(x0)) for h in hvals]
trunc_err = [truncation_err(x0, h) for h in hvals]
rounding_err = [machine_eps/h**3 for h in hvals]

# plot:
sub = plt.subplot(111)
plt.plot(hvals, abs_err, hvals, trunc_err, hvals, rounding_err)
plt.legend(['Actual Error', 'Truncation Error', 'Rounding Error'],
           loc='lower left')

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).