hw2-partial-solution
pdf
keyboard_arrow_up
School
University of Illinois, Urbana Champaign *
*We aren’t endorsed by this school
Course
370
Subject
Mathematics
Date
Apr 3, 2024
Type
Pages
28
Uploaded by elgelie7
Assignment Instructions
Complete the following problems. Then save your notebook and submit it on Gradescope (as an
.ipynb
file). Make sure you run all code cells (including assertion cells) before saving and
submitting; i.e., make sure all required outputs are visible in your submission.
Hints:
The problem parts are meant to build upon each other (i.e., your functions might call or
copy code from earlier functions).
Some functions have comments that describe the general process for my solutions. These
comments may help you think about and structure your code solutions. There are, of
course, many ways to solve these problems.
We suggest you add code cells to test your code as you work on it (it is often easier to test
code outside of a function). Just delete added cells before submitting.
Google (especially stack overflow) is your friend for code questions.
Part 0: Supplementary code
Run the following cell to access supplementary functions that may help you complete this
assignment. You can use the test cells below them to experiment and see what the functions do.
In [55]:
import
numpy as
np
def
chebyshev
(
a
, b
, n
):
"""Returns a Chebyshev point distribution of n points in the domain [a, b].
Parameters
----------
a : float_like
Lower bound of domain (inclusive)
b : float_like
Upper bound of domain (inclusive)
n : integer
Number of data points to return
Returns
-------
x : list_like
List or array of data points (in ascending order)
Examples
--------
>>> chebyshev(2, 5, 4)
array([5.0, 4.25, 2.7500000000000004, 2.0])
"""
chebyshev: [5.0, 4.25, 2.7500000000000004, 2.0]
f_true: 0.07067822452613834
Problem 1: Polynomial interpolation using
the monomial basis
We discussed in class that when performing polynomial interpolation, a linear system arises to solve for coefficients that express the interpolant in the particular basis used to build
.
This problem will have you code a solution for performing polynomial interpolation of the true
function over the interval using the monomial basis.
Use the Chebyshev points described in class.
YOUR ANSWER HERE
x =
[
0.5 *
(
a +
b
) +
0.5 *
(
b -
a
) *
np
.
cos
(
j *
np
.
pi /
(
n -
1
)) for
j in
range
(
0
,
return
x
def
f_true
(
x
):
"""Returns the value of the true function at x.
Parameters
----------
x : float_like
Input x value
Returns
-------
y : float_like
Output for f(x)
Examples
--------
>>> f_true(0.5)
array([2. , 2.75, 4.25, 5. ])
0.07067822452613834
"""
return
np
.
sin
(
np
.
cos
(
3 *
x
))
In [56]:
"""Check the function"""
# test chebyshev function
a
, b
, n =
2
, 5
, 4
x_interpolate =
chebyshev
(
a
, b
, n
)
print
(
'chebyshev: '
, x_interpolate
)
# test f_true function
x =
0.5
f =
f_true
(
x
)
print
(
'f_true: '
, f
)
1. 1. $$
\begin{bmatrix} c_0 \ c_1 \ c_2 \ c_3 \
\end{bmatrix}
$$
Part 1a: Monomial basis (concept question)
You will be asked to interpolate using a polynomial of degree with a monomial basis
.
Before coding your solution, answer the following concept questions in the next Markdown cell.
1. Write out the set of monomial basis vectors, , for your
polynomial approximation function with .
2. Symbolically derive the matrix system for using this basis (with ). I.e., show
the complete matrix equation.
Tips for writing in Jupyter notebooks:
Jupyter notebooks allow you to write in Markdown cells (like this one and the next one) and
code cells (included later in this file). Markdown is a lightweight markup language that you can
use to format text in Jupyter notebooks (and other plaintext text documents). A handy
cheatsheet for Markdown syntax can be found here: https://www.markdownguide.org/cheat-
sheet/
.
One useful aspect of Markdown is that it allows the use of LaTeX for writing math. A handy intro
to using LaTeX in Jupyter notebook Markdown cells can be found here:
https://personal.math.ubc.ca/~pwalls/math-python/jupyter/latex/
.
You can also click inside this cell to see how the matrix equation below (and the math above)
can be written in Markdown using LaTeX:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Make sure you run the cell (using SHIFT + ENTER) once you are done editing to display the
output.
Part 1b: Monomial matrix
Complete a function to return the matrix for polynomomial interpolation of degree in the
domain (i.e., using a subspace of ) with a monomial basis
.
Hints:
Use Chebyshev points (don't forget you need data points to interpolate a polynomial
of degree ).
Don't forget Python is 0-indexed.
You can initialize a 2-d numpy array (i.e., matrix) of 0's using numpy's zeros()
function:
https://numpy.org/doc/stable/reference/generated/numpy.zeros.html
.
Here is a stack overflow post discussing one way to select (or replace) the row of a 2-d
numpy array: https://stackoverflow.com/questions/26975769/modify-a-particular-row-
column-of-a-numpy-array
.
You can iterate through the indices of a list AND its elements simultaneously using Python's
enumerate()
function: https://stackoverflow.com/questions/22171558/what-does-
enumerate-mean
In [64]:
# don't forget to import any Python libraries required for your function...
def
A_monomial
(
a
, b
, n
):
"""Returns the A matrix for polynomial interpolation of degree n in the domain [a,
Parameters
----------
a : float_like
Lower bound of domain (inclusive)
b : float_like
Upper bound of domain (inclusive)
n : integer
Polynomial degree
Returns
-------
A : array_like
A matrix for polynomial interpolation satisfying Ac = f
"""
### YOUR CODE HERE ###
# get interpolation points (Chebyshev)
x_inter =
chebyshev
(
a
, b
, n +
1
)
solution: [[ 1. 5. 25. 125. ]
[ 1. 4.25 18.0625 76.765625]
[ 1. 2.75 7.5625 20.796875]
[ 1. 2. 4. 8. ]]
output: [[ 1. 5. 25. 125. ]
[ 1. 4.25 18.0625 76.765625]
[ 1. 2.75 7.5625 20.796875]
[ 1. 2. 4. 8. ]]
TESTS PASSED
Part 1c: Monomial solution
Complete a function to return:
the vector of coefficients for polynomomial interpolation of degree in the domain with a monomial basis
,
the matrix,
the condition number of the matrix.
The condition number of a matrix is a measure of how sensitive a matrix system is to
perturbation error. The condition number is defined as and varies between and
. The larger the condition number, the more sensitive the system is to perturbation.
Requirements:
Use numpy's linalg.inv()
function to calculate the inverse of .
Do NOT use numpy's linalg.solve()
function for this exercise (or any other pre-built
matrix solver).
# build A matrix
A =
np
.
zeros
((
n +
1
, n +
1
)) # initialize n+1 x n+1 matrix of 0's
for
row
, x in
enumerate
(
x_inter
): # loop through each interpolation point (i.e., e
# print(x, row_num) # for debugging
row_val =
np
.
zeros
(
n +
1
) # initialize n+1 vector of 0's for current row of for
k in
range
(
n +
1
): # loop through each column of A (i.e., each basis)
row_val
[
k
] =
x **
k
A
[
row
] =
row_val # update current row of A
# # build A matrix (alternate)
# A = np.zeros((n + 1, n + 1))
# for row_num, x in enumerate(x_interpolate): # loop through each interpolation po
# A[row_num] = [x ** k for k in range(n + 1)] # an alternative 1-liner that c
return
A
In [65]:
"""Check the function"""
a
, b
, n =
2
, 5
, 3
A =
A_monomial
(
a
, b
, n
)
# check output
A_solution =
np
.
array
([[
1
, 5
, 25
, 125
], [
1
, 4.25
, 18.0625
, 76.765625
], [
1
, 2.75
, 7.562
print
(
'solution: '
, A_solution
)
print
(
'output: '
, A
)
np
.
testing
.
assert_allclose
(
A
, A_solution
)
print
(
'TESTS PASSED'
)
Use numpy's linalg.cond()
function to calculate .
Assume your f_true()
function is globally defined and accessible within your function.
In [70]:
# don't forget to import any Python libraries required for your function...
def
solve_monomial
(
a
, b
, n
):
"""Returns the solution to polynomial interpolation of degree n in the domain [a, This function assumes an f_true(x) function is globally available for calculating Parameters
----------
a : float_like
Lower bound of domain (inclusive)
b : float_like
Upper bound of domain (inclusive)
n : integer
Polynomial degree
Returns
-------
c : array_like
c vector of coefficients for polynomial interpolation satisfying Ac = f
A : array_like
A matrix for polynomial interpolation satisfying Ac = f
condition : float_like
Condition number for the A matrix
"""
### YOUR CODE HERE ###
# get interpolation points (Chebyshev)
x_inter =
chebyshev
(
a
, b
, n +
1
)
# build A matrix (alternate)
A =
np
.
zeros
((
n +
1
, n +
1
))
for
row
, x in
enumerate
(
x_inter
): # loop through each interpolation point (i.e., e
A
[
row
] =
[
x **
k for
k in
range
(
n +
1
)] # an alternative 1-liner that can rep
# get f (vector of true function values for interpolation points)
f =
[
f_true
(
x
) for
x in
x_inter
]
# solve matrix system
c =
np
.
linalg
.
inv
(
A
)
.
dot
(
f
)
# get cond(A)
condition =
np
.
linalg
.
cond
(
A
)
return
c
, A
, condition
In [71]:
"""Check the function"""
a
, b
, n =
2
, 5
, 3
c
, A
, condition =
solve_monomial
(
a
, b
, n
)
# check output
c_solution =
np
.
array
([
27.99638068
, -
26.57603744
, 8.04437345
, -
0.7753138
])
A_solution =
np
.
array
([[
1
, 5
, 25
, 125
], [
1
, 4.25
, 18.0625
, 76.765625
], [
1
, 2.75
, 7.562
condition_solution =
5004.3550034210
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
c solution: [ 27.99638068 -26.57603744 8.04437345 -0.7753138 ]
A solution: [[ 1. 5. 25. 125. ]
[ 1. 4.25 18.0625 76.765625]
[ 1. 2.75 7.5625 20.796875]
[ 1. 2. 4. 8. ]]
Condition(A) solution: 5004.355003421
c output: [ 27.99638068 -26.57603744 8.04437345 -0.7753138 ]
A output: [[ 1. 5. 25. 125. ]
[ 1. 4.25 18.0625 76.765625]
[ 1. 2.75 7.5625 20.796875]
[ 1. 2. 4. 8. ]]
Condition(A) output: 5004.3550034211
TESTS PASSED
Part 1d: Monomial approximation
Complete a function to return:
the approximated values for all , where is a polynomomial
interpolation in the domain with a monomial basis
,
the true values for all ,
the approximation error for .
Calculate the error as , where .
Requirements:
Assume .
Assume your f_true()
function is globally defined and accessible within your function.
print
(
'c solution: '
, c_solution
)
print
(
'A solution: '
, A_solution
)
print
(
'Condition(A) solution: '
, condition_solution
)
print
(
'c output: '
, c
)
print
(
'A output: '
, A
)
print
(
'Condition(A) output: '
, condition
)
np
.
testing
.
assert_allclose
(
c
, c_solution
)
np
.
testing
.
assert_allclose
(
A
, A_solution
)
np
.
testing
.
assert_almost_equal
(
condition
, condition_solution
)
print
(
'TESTS PASSED'
)
In [72]:
# don't forget to import any Python libraries required for your function...
def
approximate_monomial
(
c
, x_test
):
"""Returns the interpolation error for a polynomial with a monomial basis.
This function assumes an f_true(x) function is globally available for calculating Parameters
----------
c : array_like
c vector for polynomial interpolation satisfying Ac = f
x_test : array_like
List of inputs to evaluate the approximated function over
Returns
error solution: 1.1032593316064347
error output: 1.1032593316064347
TESTS PASSED
Part 1e: Monomial experiment
Write code to create the following (separate) plots:
1. plot the approximated and true function for polynomial degrees (make a
subplot with one subplot for each ),
2. plot the approximation error as a function of polynomial degree for ,
3. plot the condition number for as a function of polynomial degree for .
Define as 1000 equally spaced points in the domain.
-------
fa : array_like
Vector of approximated function values for each x in x_test
f : array_like
Vector of true function
err : float_like
Error calculated as a 2-norm using x_test
"""
### YOUR CODE HERE ###
# get fa (vector of approximated function values for x_test)
fa =
[]
n =
len
(
c
) -
1 # polynomial degree
for
x in
x_test
:
fa_t =
[
coeff *
(
x **
k
) for
coeff
, k in
zip
(
c
, range
(
n +
1
))]
fa
.
append
(
sum
(
fa_t
))
# get f (vector of true function values for x_test)
f =
np
.
array
([
f_true
(
x
) for
x in
x_test
])
# get e (error vector)
e =
f -
fa
# calculate error (2-norm)
err =
np
.
sqrt
(
np
.
dot
(
e
, e
))
# err = np.linalg.norm(e)
return
fa
, f
, err
In [73]:
"""Check the function"""
c =
np
.
array
([
27.99638068
, -
26.57603744
, 8.04437345
, -
0.7753138
])
a
, b =
2
, 5
x_test =
np
.
linspace
(
a
, b
, 7
)
fa
, f
, err =
approximate_monomial
(
c
, x_test
)
# check output
err_sol =
1.1032593316064347
print
(
'error solution: '
, err_sol
)
print
(
'error output: '
, err
)
np
.
testing
.
assert_almost_equal
(
err
, err_sol
)
print
(
'TESTS PASSED'
)
Hints:
Use matplotlib's tight_layout()
function to help with subplot axes arrangement. E.g.,
create your figure using fig = plt.figure(figsize=(6, 4), tight_layout=True)
.
In [76]:
### YOUR CODE HERE ###
import
matplotlib.pyplot as
plt
plt
.
style
.
use
(
'default'
)
# define a, b, n values and x_test points
a
, b =
2
, 5
n_list =
[
3
, 10
, 20
, 40
]
x_t =
np
.
linspace
(
a
, b
, 1000
)
# initialize lists for saving data
x_inter_list =
[]
f_inter_list =
[]
fa_list =
[]
f_list =
[]
err_list =
[]
condition_list =
[]
# get data for each degree n
for
n in
n_list
:
# get interpolation points (Chebyshev)
x_inter =
chebyshev
(
a
, b
, n +
1
)
# get true function values for interpolation points (for plotting)
f_inter =
[
f_true
(
x
) for
x in
x_inter
]
# get monomial solution
c
, A
, condition =
solve_monomial
(
a
, b
, n
)
# get monomial approximation for x_test
fa
, f
, err =
approximate_monomial
(
c
, x_t
)
# save data to lists
x_inter_list
.
append
(
x_inter
)
f_inter_list
.
append
(
f_inter
)
fa_list
.
append
(
fa
)
f_list
.
append
(
f
)
err_list
.
append
(
err
)
condition_list
.
append
(
condition
)
# plot interpolated and true functions
fig =
plt
.
figure
(
figsize
=
(
8
, 6
), tight_layout
=
True
)
ax1 =
fig
.
add_subplot
(
221
)
ax1
.
plot
(
x_t
, f_list
[
0
], 'k-'
, label
=
'$f(x)$'
)
ax1
.
plot
(
x_t
, fa_list
[
0
], 'r--'
, label
=
'$f_a(x)$'
)
ax1
.
plot
(
x_inter_list
[
0
], f_inter_list
[
0
], 'bo'
, label
=
'$f(x_j)$'
)
ax1
.
set_xlabel
(
'$x$'
)
ax1
.
set_ylabel
(
''
)
ax1
.
set_ylim
(
-
1
, 1
)
ax1
.
set_title
(
'$n$ = 3'
)
ax1
.
legend
()
ax2 =
fig
.
add_subplot
(
222
)
ax2
.
plot
(
x_t
, f_list
[
1
], 'k-'
, label
=
'$f(x)$'
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ax2
.
plot
(
x_t
, fa_list
[
1
], 'r--'
, label
=
'$f_a(x)$'
)
ax2
.
plot
(
x_inter_list
[
1
], f_inter_list
[
1
], 'bo'
, label
=
'$f(x_j)$'
)
ax2
.
set_xlabel
(
'$x$'
)
ax2
.
set_ylabel
(
''
)
ax2
.
set_ylim
(
-
1
, 1
)
ax2
.
set_title
(
'$n$ = 10'
)
ax2
.
legend
()
ax3 =
fig
.
add_subplot
(
223
)
ax3
.
plot
(
x_t
, f_list
[
2
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
2
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
2
], f_inter_list
[
2
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 20'
)
ax3
.
legend
()
ax3 =
fig
.
add_subplot
(
224
)
ax3
.
plot
(
x_t
, f_list
[
3
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
3
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
3
], f_inter_list
[
3
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 40'
)
ax3
.
legend
()
fig
.
savefig
(
'solution-figures/part1e-functions.png'
)
# plot error vs. n
fig =
plt
.
figure
(
figsize
=
(
4
, 3
), tight_layout
=
True
)
ax =
fig
.
add_subplot
(
111
)
ax
.
plot
(
n_list
, err_list
, 'ko'
)
ax
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax
.
set_ylabel
(
'Error, $||e||$'
)
ax
.
set_yscale
(
'log'
)
fig
.
savefig
(
'solution-figures/part1e-error.png'
)
# plot condition number vs. n
fig =
plt
.
figure
(
figsize
=
(
4
, 3
), tight_layout
=
True
)
ax =
fig
.
add_subplot
(
111
)
ax
.
plot
(
n_list
, condition_list
, 'ko'
)
ax
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax
.
set_ylabel
(
'Condition Number, $\kappa(A)$'
)
ax
.
set_yscale
(
'log'
)
fig
.
savefig
(
'solution-figures/part1e-condition.png'
)
---------------------------------------------------------------------------
FileNotFoundError
Traceback (most recent call last)
Cell In[76], line 79
77 ax3
.
set_title(
'$n$ = 40'
)
78 ax3
.
legend()
---> 79
fig
.
savefig(
'solution-figures/part1e-functions.png'
)
81 # plot error vs. n
82 fig = plt
.
figure(figsize
=
(
4
, 3
), tight_layout
=
True
)
File ~\anaconda3\Lib\site-packages\matplotlib\figure.py:3378
, in Figure.savefig
(self, fname, transparent, **kwargs)
3374 for
ax in
self
.
axes:
3375 stack
.
enter_context(
3376 ax
.
patch
.
_cm_set(facecolor
=
'none'
, edgecolor
=
'none'
))
-> 3378
self
.
canvas
.
print_figure(fname, **
kwargs)
File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2366
, in FigureCanvasB
ase.print_figure
(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox
_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2362 try
:
2363 # _get_renderer may change the figure dpi (as vector formats
2364 # force the figure dpi to 72), so we need to set it again here.
2365 with
cbook
.
_setattr_cm(
self
.
figure, dpi
=
dpi):
-> 2366
result = print_method(
2367 filename,
2368 facecolor
=
facecolor,
2369 edgecolor
=
edgecolor,
2370 orientation
=
orientation,
2371 bbox_inches_restore
=
_bbox_inches_restore,
2372 **
kwargs)
2373 finally
:
2374 if
bbox_inches and
restore_bbox:
File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2232
, in FigureCanvasB
ase._switch_canvas_and_return_print_method.<locals>.<lambda>
(*args, **kwargs)
2228 optional_kws = { # Passed by print_figure for other renderers.
2229 "dpi"
, "facecolor"
, "edgecolor"
, "orientation"
,
2230 "bbox_inches_restore"
}
2231 skip = optional_kws - {
*
inspect
.
signature(meth)
.
parameters}
-> 2232
print_method = functools
.
wraps(meth)(
lambda
*
args, **
kwargs: meth(
2233 *
args, **
{k: v for
k, v in
kwargs
.
items() if
k not
in
skip}))
2234 else
: # Let third-parties do as they see fit.
2235 print_method = meth
File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:509
, in FigureC
anvasAgg.print_png
(self, filename_or_obj, metadata, pil_kwargs)
462 def
print_png
(
self
, filename_or_obj, *
, metadata
=
None
, pil_kwargs
=
None
):
463 """
464 Write the figure to a PNG file.
465 (...)
507 *metadata*, including the default 'Software' key.
508 """
--> 509
self
.
_print_pil(filename_or_obj, "png"
, pil_kwargs, metadata)
File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:458
, in FigureC
anvasAgg._print_pil
(self, filename_or_obj, fmt, pil_kwargs, metadata)
453 """
454 Draw the canvas, then save it using `.image.imsave` (to which
455 *pil_kwargs* and *metadata* are forwarded).
456 """
457 FigureCanvasAgg
.
draw(
self
)
--> 458
mpl
.
image
.
imsave(
459 filename_or_obj, self
.
buffer_rgba(), format
=
fmt, origin
=
"upper"
,
460 dpi
=
self
.
figure
.
dpi, metadata
=
metadata, pil_kwargs
=
pil_kwargs)
File ~\anaconda3\Lib\site-packages\matplotlib\image.py:1689
, in imsave
(fname, arr, vm
in, vmax, cmap, format, origin, dpi, metadata, pil_kwargs)
1687 pil_kwargs
.
setdefault(
"format"
, format
)
1688 pil_kwargs
.
setdefault(
"dpi"
, (dpi, dpi))
-> 1689
image
.
save(fname, **
pil_kwargs)
File ~\anaconda3\Lib\site-packages\PIL\Image.py:2428
, in Image.save
(self, fp, format, **params)
2426 fp = builtins
.
open(filename, "r+b"
)
2427 else
:
-> 2428
fp = builtins
.
open(filename, "w+b"
)
2430 try
:
2431 save_handler(
self
, fp, filename)
FileNotFoundError
: [Errno 2] No such file or directory: 'solution-figures/part1e-func
tions.png'
Problem 2: Is the Lagrange basis really better
than the monomial basis for polynomial
interpolation?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
We discussed in class that the Lagrange basis is vastly superior to the monomial basis. You will
demonstrate that for yourself in this problem.
Use the Chebyshev points described in class.
Part 2a: Lagrange basis (concept question)
You will be asked to interpolate using a polynomial of degree with a Lagrange basis
.
Before coding your solution, answer the following concept questions in the next Markdown cell.
1. Write out the set of Lagrange basis vectors, , for your
polynomial approximation function with .
2. Symbolically derive the matrix system for using this basis (with ). I.e., show
the complete matrix equation.
YOUR ANSWER HERE x_interpolate = chebyshev(a, b, n + 1)
# build A matrix (alternate)
A=np.identity(np.size(x_interpolate))
# get f (vector of true function values for interpolation points)
f = [f_true(x) for x in x_interpolate]
# solve matrix system
c = np.linalg.inv(A).dot(f)
Part 2b: Lagrange solution and approximation
Complete a function to return:
the vector of coefficients for polynomomial interpolation of degree in the domain with a Lagrange basis
,
the matrix,
the condition number of the matrix,
the interpolation points used.
Complete a function to return:
the approximated values for all , where is a polynomomial
interpolation in the domain with a Lagrange basis
,
the true values for all ,
the approximation error for .
Calculate the error as , where .
In [101…
def
lag
(
c
,
x
,
x_int
):
L =
[]
n =
np
.
size
(
c
) -
1 # polynomial degree
for
p in
range
(
n
+
1
):
poly
=
1
for
i in
range
(
n
+
1
):
if
p
!=
i
:
poly *=
(
x
-
x_int
[
i
])
poly /=
(
x_int
[
p
]
-
x_int
[
i
])
L
.
append
(
poly
)
fa_terms =
[
coeff *
polynomial for
coeff
, polynomial in
zip
(
c
, L
)]
val
=
sum
(
fa_terms
)
return
val
In [102…
# don't forget to import any Python libraries required for your function...
def
solve_lagrange
(
a
, b
, n
):
"""Returns the solution to polynomial interpolation of degree n in the domain [a, This function assumes an f_true(x) function is globally available for calculating Parameters
----------
a : float_like
Lower bound of domain (inclusive)
b : float_like
Upper bound of domain (inclusive)
n : integer
Polynomial degree
Returns
-------
c : array_like
c vector of coefficients for polynomial interpolation satisfying Ac = f
A : array_like
A matrix for polynomial interpolation satisfying Ac = f
condition : float_like
Condition number for the A matrix
x_interpolate : array_like
List of interpolation points (i.e., x-values) used
"""
x_interpolate =
chebyshev
(
a
, b
, n +
1
)
# build A matrix (alternate)
A
=
np
.
identity
(
np
.
size
(
x_interpolate
))
# get f (vector of true function values for interpolation points)
f =
[
f_true
(
x
) for
x in
x_interpolate
]
# solve matrix system
c =
np
.
linalg
.
inv
(
A
)
.
dot
(
f
)
# get cond(A)
condition =
np
.
linalg
.
cond
(
A
)
return
c
, A
, condition
,
x_interpolate
### YOUR CODE HERE ###
# get interpolation points (Chebyshev)
# build A matrix
# get f (vector of true function values for interpolation points)
# solve matrix system
# get cond(A)
def
approximate_lagrange
(
c
, x_interpolate
, x_test
):
"""Returns the interpolation error for a polynomial with a Lagrange basis.
This function assumes an f_true(x) function is globally available for calculating Parameters
----------
c : array_like
c vector for polynomial interpolation satisfying Ac = f
x_interpolate : array_like
List of interpolation points (i.e., x-values) used
x_test : array_like
List of inputs to evaluate the approximated function over
Returns
-------
fa : array_like
Vector of approximated function values for each x in x_test
f : array_like
Vector of true function
err : float_like
Error calculated as a 2-norm using x_test
"""
fa
=
[
lag
(
c
,
x
,
x_interpolate
) for
x in
x_test
]
# get f (vector of true function values for x_test)
f =
np
.
array
([
f_true
(
x
) for
x in
x_test
])
# get e (error vector)
e =
f -
fa
# calculate error (2-norm)
err =
np
.
sqrt
(
np
.
dot
(
e
, e
))
# err = np.linalg.norm(e)
return
fa
, f
, err
### YOUR CODE HERE ###
# get fa (vector of approximated function values for x_test)
# get f (vector of true function values for x_test)
# get e (error vector)
# calculate error (2-norm)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
c solution: [-0.6886952 0.83226863 -0.37625222 0.81928922]
A solution: [[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
Condition(A) solution: 1
Interpolation points solution: [5, 4.25, 2.75, 2]
c output: [-0.6886952 0.83226863 -0.37625222 0.81928922]
A output: [[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Condition(A) output: 1.0
Interpolation points output: [5.0, 4.25, 2.7500000000000004, 2.0]
TESTS PASSED
In [103…
"""Check the solve_lagrange function"""
a
, b
, n =
2
, 5
, 3
c
, A
, condition
, x_interpolate =
solve_lagrange
(
a
, b
, n
)
# check output
c_sol =
np
.
array
([
-
0.6886951995658905
, 0.8322686285099006
, -
0.37625221889548544
, 0.819
A_sol =
np
.
array
([[
1
, 0
, 0
, 0
], [
0
, 1
, 0
, 0
], [
0
, 0
, 1
, 0
], [
0
, 0
, 0
, 1
]])
cond_sol =
1
x_sol =
[
5
, 4.25
, 2.75
, 2
]
print
(
'c solution: '
, c_sol
)
print
(
'A solution: '
, A_sol
)
print
(
'Condition(A) solution: '
, cond_sol
)
print
(
'Interpolation points solution: '
, x_sol
)
print
(
'c output: '
, c
)
print
(
'A output: '
, A
)
print
(
'Condition(A) output: '
, condition
)
print
(
'Interpolation points output: '
, x_interpolate
)
np
.
testing
.
assert_allclose
(
c
, c_sol
)
np
.
testing
.
assert_allclose
(
A
, A_sol
)
np
.
testing
.
assert_almost_equal
(
condition
, cond_sol
)
np
.
testing
.
assert_allclose
(
x_interpolate
, x_sol
)
print
(
'TESTS PASSED'
)
In [104…
"""Check the approximate_lagrange function"""
a
, b
, n =
2
, 5
, 3
c =
[
0.819289219220601
, -
0.37625221889548544
, 0.8322686285099006
, -
0.6886951995658905
]
x_interpolate =
[
2
, 2.75
, 4.25
, 5
]
x_test =
np
.
linspace
(
a
, b
, 7
)
fa
, f
, err =
approximate_lagrange
(
c
, x_interpolate
, x_test
)
# check output
fa_sol =
[
0.819289219220601
, -
0.28065695641855654
, -
0.2658431561710738
, 0.282245269800
f_sol =
[
0.81928922
, 0.33973518
, -
0.79019693
, -
0.45781587
, 0.74720996
, 0.56044305
, -
0.
err_sol =
1.1032593680772769
print
(
'fa solution: '
, fa_sol
)
print
(
'f solution: '
, f_sol
)
print
(
'err solution: '
, err_sol
)
print
(
'fa output: '
, fa
)
print
(
'f output: '
, f
)
print
(
'err output: '
, err
)
np
.
testing
.
assert_allclose
(
fa
, fa_sol
)
np
.
testing
.
assert_allclose
(
f
, f_sol
)
np
.
testing
.
assert_almost_equal
(
err
, err_sol
)
fa solution: [0.819289219220601, -0.28065695641855654, -0.2658431561710738, 0.282245
2698004917, 0.7821229713335826, 0.652304598265641, -0.6886951995658905]
f solution: [0.81928922, 0.33973518, -0.79019693, -0.45781587, 0.74720996, 0.5604430
5, -0.6886952]
err solution: 1.1032593680772769
fa output: [0.819289219220601, -0.28065695641855654, -0.2658431561710738, 0.28224526
98004917, 0.7821229713335826, 0.652304598265641, -0.6886951995658905]
f output: [ 0.81928922 0.33973518 -0.79019693 -0.45781587 0.74720996 0.56044305
-0.6886952 ]
err output: 1.1032593680772769
TESTS PASSED
Part 2c: Lagrange vs. monomial experiment
Write code to create the following (separate) plots:
1. plot the approximated and true function for polynomial degrees (make a
subplot with one subplot for each ),
2. plot the approximation error as a function of polynomial degree for for
the monomial AND Lagrange bases
,
3. plot the condition number for as a function of polynomial degree for for the monomial AND Lagrange bases
.
Define as 1000 equally spaced points in the domain.
Hints:
Use matplotlib's tight_layout()
function to help with subplot axes arrangement. E.g.,
create your figure using fig = plt.figure(figsize=(6, 4), tight_layout=True)
.
print
(
'TESTS PASSED'
)
print
(
' '
)
In [108…
### YOUR CODE HERE ###
# define a, b, n values and x_test points
# initialize lists for saving data
# get data for each degree n
# get interpolation points (Chebyshev)
# get true function values for interpolation points (for plotting)
# get monomial and Lagrange solutions
# get monomial and Lagrange approximations for x_test
# save data to lists
# plot interpolated and true functions (Lagrange)
# plot error vs. n
# plot condition number vs. n
a
, b =
2
, 5
n_list =
[
3
, 10
, 20
, 40
]
x_t =
np
.
linspace
(
a
, b
, 1000
)
# initialize lists for saving data
x_inter_list =
[]
f_inter_list =
[]
fa_list =
[]
f_list =
[]
err_list =
[]
condition_list =
[]
fa_list_l =
[]
f_list_l =
[]
err_list_l =
[]
condition_list_l =
[]
# get data for each degree n
for
n in
n_list
:
# get interpolation points (Chebyshev)
x_interpolation =
chebyshev
(
a
, b
, n +
1
)
# get true function values for interpolation points (for plotting)
f_inter =
[
f_true
(
x
) for
x in
x_interpolation
]
# get monomial solution
c
, A
, condition =
solve_monomial
(
a
, b
, n
)
cl
, Al
, conditionl
,
x_interpolate
=
solve_lagrange
(
a
, b
, n
)
# get monomial approximation for x_test
fa
, f
, err =
approximate_monomial
(
c
, x_t
)
fal
, fl
, errl =
approximate_lagrange
(
c
, x_interpolate
, x_test
)
# save data to lists
x_inter_list
.
append
(
x_interpolation
)
f_inter_list
.
append
(
f_inter
)
fa_list
.
append
(
fa
)
f_list
.
append
(
f
)
err_list
.
append
(
err
)
condition_list
.
append
(
condition
)
fa_list_l
.
append
(
fal
)
f_list_l
.
append
(
fl
)
err_list_l
.
append
(
errl
)
condition_list_l
.
append
(
conditionl
)
# plot interpolated and true functions
fig =
plt
.
figure
(
figsize
=
(
8
, 6
), tight_layout
=
True
)
ax1 =
fig
.
add_subplot
(
221
)
ax1
.
plot
(
x_t
, f_list
[
0
], 'k-'
, label
=
'$f(x)$'
)
ax1
.
plot
(
x_t
, fa_list
[
0
], 'r--'
, label
=
'$f_a(x)$'
)
ax1
.
plot
(
x_inter_list
[
0
], f_inter_list
[
0
], 'bo'
, label
=
'$f(x_j)$'
)
ax1
.
set_xlabel
(
'$x$'
)
ax1
.
set_ylabel
(
''
)
ax1
.
set_ylim
(
-
1
, 1
)
ax1
.
set_title
(
'$n$ = 3'
)
ax1
.
legend
()
ax2 =
fig
.
add_subplot
(
222
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ax2
.
plot
(
x_t
, f_list
[
1
], 'k-'
, label
=
'$f(x)$'
)
ax2
.
plot
(
x_t
, fa_list
[
1
], 'r--'
, label
=
'$f_a(x)$'
)
ax2
.
plot
(
x_inter_list
[
1
], f_inter_list
[
1
], 'bo'
, label
=
'$f(x_j)$'
)
ax2
.
set_xlabel
(
'$x$'
)
ax2
.
set_ylabel
(
''
)
ax2
.
set_ylim
(
-
1
, 1
)
ax2
.
set_title
(
'$n$ = 10'
)
ax2
.
legend
()
ax3 =
fig
.
add_subplot
(
223
)
ax3
.
plot
(
x_t
, f_list
[
2
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
2
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
2
], f_inter_list
[
2
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 20'
)
ax3
.
legend
()
ax3 =
fig
.
add_subplot
(
224
)
ax3
.
plot
(
x_t
, f_list
[
3
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
3
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
3
], f_inter_list
[
3
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 40'
)
ax3
.
legend
()
fig
.
savefig
(
'solution-figures/part1e-functions.png'
)
# plot error vs. n
fig =
plt
.
figure
(
figsize
=
(
4
, 3
), tight_layout
=
True
)
ax =
fig
.
add_subplot
(
111
)
ax
.
plot
(
n_list
, err_list
, 'ko'
)
ax
.
plot
(
n_list
, err_list_l
, 'r'
)
ax
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax
.
set_ylabel
(
'Error, $||e||$'
)
ax
.
set_yscale
(
'log'
)
fig
.
savefig
(
'solution-figures/part1e-error.png'
)
# plot condition number vs. n
fig =
plt
.
figure
(
figsize
=
(
4
, 3
), tight_layout
=
True
)
ax =
fig
.
add_subplot
(
111
)
ax
.
plot
(
n_list
, condition_list
, 'ko'
)
ax
.
plot
(
n_list
, condition_list_l
, 'ko'
)
ax
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax
.
set_ylabel
(
'Condition Number, $\kappa(A)$'
)
ax
.
set_yscale
(
'log'
)
fig
.
savefig
(
'solution-figures/part1e-condition.png'
)
---------------------------------------------------------------------------
FileNotFoundError
Traceback (most recent call last)
Cell In[108], line 109
107 ax3
.
set_title(
'$n$ = 40'
)
108 ax3
.
legend()
--> 109
fig
.
savefig(
'solution-figures/part1e-functions.png'
)
111 # plot error vs. n
112 fig = plt
.
figure(figsize
=
(
4
, 3
), tight_layout
=
True
)
File ~\anaconda3\Lib\site-packages\matplotlib\figure.py:3378
, in Figure.savefig
(self, fname, transparent, **kwargs)
3374 for
ax in
self
.
axes:
3375 stack
.
enter_context(
3376 ax
.
patch
.
_cm_set(facecolor
=
'none'
, edgecolor
=
'none'
))
-> 3378
self
.
canvas
.
print_figure(fname, **
kwargs)
File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2366
, in FigureCanvasB
ase.print_figure
(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox
_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2362 try
:
2363 # _get_renderer may change the figure dpi (as vector formats
2364 # force the figure dpi to 72), so we need to set it again here.
2365 with
cbook
.
_setattr_cm(
self
.
figure, dpi
=
dpi):
-> 2366
result = print_method(
2367 filename,
2368 facecolor
=
facecolor,
2369 edgecolor
=
edgecolor,
2370 orientation
=
orientation,
2371 bbox_inches_restore
=
_bbox_inches_restore,
2372 **
kwargs)
2373 finally
:
2374 if
bbox_inches and
restore_bbox:
File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2232
, in FigureCanvasB
ase._switch_canvas_and_return_print_method.<locals>.<lambda>
(*args, **kwargs)
2228 optional_kws = { # Passed by print_figure for other renderers.
2229 "dpi"
, "facecolor"
, "edgecolor"
, "orientation"
,
2230 "bbox_inches_restore"
}
2231 skip = optional_kws - {
*
inspect
.
signature(meth)
.
parameters}
-> 2232
print_method = functools
.
wraps(meth)(
lambda
*
args, **
kwargs: meth(
2233 *
args, **
{k: v for
k, v in
kwargs
.
items() if
k not
in
skip}))
2234 else
: # Let third-parties do as they see fit.
2235 print_method = meth
File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:509
, in FigureC
anvasAgg.print_png
(self, filename_or_obj, metadata, pil_kwargs)
462 def
print_png
(
self
, filename_or_obj, *
, metadata
=
None
, pil_kwargs
=
None
):
463 """
464 Write the figure to a PNG file.
465 (...)
507 *metadata*, including the default 'Software' key.
508 """
--> 509
self
.
_print_pil(filename_or_obj, "png"
, pil_kwargs, metadata)
File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:458
, in FigureC
anvasAgg._print_pil
(self, filename_or_obj, fmt, pil_kwargs, metadata)
453 """
454 Draw the canvas, then save it using `.image.imsave` (to which
455 *pil_kwargs* and *metadata* are forwarded).
456 """
457 FigureCanvasAgg
.
draw(
self
)
--> 458
mpl
.
image
.
imsave(
459 filename_or_obj, self
.
buffer_rgba(), format
=
fmt, origin
=
"upper"
,
460 dpi
=
self
.
figure
.
dpi, metadata
=
metadata, pil_kwargs
=
pil_kwargs)
File ~\anaconda3\Lib\site-packages\matplotlib\image.py:1689
, in imsave
(fname, arr, vm
in, vmax, cmap, format, origin, dpi, metadata, pil_kwargs)
1687 pil_kwargs
.
setdefault(
"format"
, format
)
1688 pil_kwargs
.
setdefault(
"dpi"
, (dpi, dpi))
-> 1689
image
.
save(fname, **
pil_kwargs)
File ~\anaconda3\Lib\site-packages\PIL\Image.py:2428
, in Image.save
(self, fp, format, **params)
2426 fp = builtins
.
open(filename, "r+b"
)
2427 else
:
-> 2428
fp = builtins
.
open(filename, "w+b"
)
2430 try
:
2431 save_handler(
self
, fp, filename)
FileNotFoundError
: [Errno 2] No such file or directory: 'solution-figures/part1e-func
tions.png'
Part 2d: Discussion (concept question)
Discuss the following in the Markdown cell below.
1. Use the plots from Part 2c to argue why the Lagrange basis is betted suited to polynomial
interpolation than the monomial basis.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
2. Why does the monomial basis still give large errors even when using Chebyshev points?
YOUR ANSWER HERE because they are increasingly simallar
Problem 3: The importance of point
distribution in polynomial interpolation
Runge's problem is a famous case of when polynomial interpolation can go dramatically wrong.
In fact, it is one of the primary reasons why many experts believe that polynomial interpolation
is doomed to fail, when this is in fact not true
provided that one uses the right set of
interpolation points!
We will investigate behavior of polynomial interpolants on Runge's problem now: consider
interpolating over the interval .
Hint:
You may want to redefine the f_true()
function to be for this problem.
Just make sure you re-run the original f_true()
function to set if
you re-run code for Problems 1 and 2 after running code for this problem. You can also
modify the Lagrange functions created earlier to have an input argument specifying which
to assume.
Part 3a: Interpolation using equally spaced points
Write code to interpolate using equally spaced points with the Lagrange basis for
polynomials of degree .
In [109…
def
f_trued
(
x
):
"""Returns the value of the true function at x.
Parameters
----------
x : float_like
Input x value
Returns
-------
y : float_like
Output for f(x)
Examples
--------
>>> f_true(0.5)
array([2. , 2.75, 4.25, 5. ])
0.07067822452613834
"""
return
1
/
(
1
+
x
^
2
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
In [110…
def
solve_lagrange_equispaced
(
a
, b
, n
):
"""Returns the solution to polynomial interpolation of degree n in the domain [a, This function assumes an f_true(x) function is globally available for calculating Parameters
----------
a : float_like
Lower bound of domain (inclusive)
b : float_like
Upper bound of domain (inclusive)
n : integer
Polynomial degree
Returns
-------
c : array_like
c vector of coefficients for polynomial interpolation satisfying Ac = f
A : array_like
A matrix for polynomial interpolation satisfying Ac = f
condition : float_like
Condition number for the A matrix
x_interpolate : array_like
List of interpolation points (i.e., x-values) used
"""
x_interpolate =
np
.
linspace
(
a
, b
, n
+
1
)
# build A matrix (alternate)
A
=
np
.
identity
(
np
.
size
(
x_interpolate
))
# get f (vector of true function values for interpolation points)
f =
[
f_trued
(
x
) for
x in
x_interpolate
]
# solve matrix system
c =
np
.
linalg
.
inv
(
A
)
.
dot
(
f
)
# get cond(A)
condition =
np
.
linalg
.
cond
(
A
)
return
c
, A
, condition
,
x_interpolate
### YOUR CODE HERE ###
# get interpolation points
# build A matrix
# get f (vector of true function values for interpolation points)
# solve matrix system
# get cond(A)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Part 3b: Equally spaced vs. Chebyshev points
experiment
Write code to create the following (separate) plots:
1. plot the approximated and true function for polynomial interpolation using the Lagrange
basis with degrees (make a subplot with one subplot for each ) when using
equally spaced points AND Chebyshev points
,
2. plot the approximation error as a function of polynomial degree for when
using equally spaced AND Chebyshev points
.
Define as 1000 equally spaced points in the domain.
In [111…
### YOUR CODE HERE ###
# redefine f_true
# define a, b, n values and x_test points
# initialize lists for saving data
# get data for each degree n
# get equal and Chebyshev solutions
# get monomial and Lagrange approximations for x_test
# save data to lists
# plot interpolated and true functions
a
, b =
-
5
, 5
n_list =
[
5
, 10
, 20
]
x_t =
np
.
linspace
(
a
, b
, 1000
)
# initialize lists for saving data
x_inter_list =
[]
x_equalspace
=
[]
f_inter_list =
[]
f_inter_list_eq
=
[]
fa_list_l =
[]
f_list_l =
[]
err_list_l =
[]
condition_list_l =
[]
# get data for each degree n
for
n in
n_list
:
# get interpolation points (Chebyshev)
x_interpolation =
chebyshev
(
a
, b
, n +
1
)
x_interpolate =
np
.
linspace
(
a
, b
, n
+
1
)
# get true function values for interpolation points (for plotting)
f_inter =
[
f_true
(
x
) for
x in
x_interpolation
]
f_inter_eq
=
[
f_trued
(
x
) for
x in
x_interpolate
]
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
# get monomial solution
cl
, Al
, conditionl
,
x_interpolate
=
solve_lagrange
(
a
, b
, n
)
cleq
, Aleq
, conditionleq
,
x_interpolate
=
solve_lagrange_equispaced
(
a
, b
, n
)
# get monomial approximation for x_test
fal
, fl
, errl =
approximate_lagrange
(
c
, x_interpolate
, x_test
)
fal
, fl
, errl =
approximate_lagrange
(
c
, x_interpolate
, x_test
)
# save data to lists
x_inter_list
.
append
(
x_interpolation
)
f_inter_list
.
append
(
f_inter
)
fa_list
.
append
(
fa
)
f_list
.
append
(
f
)
err_list
.
append
(
err
)
condition_list
.
append
(
condition
)
fa_list_l
.
append
(
fal
)
f_list_l
.
append
(
fl
)
err_list_l
.
append
(
errl
)
condition_list_l
.
append
(
conditionl
)
# plot interpolated and true functions
fig =
plt
.
figure
(
figsize
=
(
8
, 6
), tight_layout
=
True
)
ax1 =
fig
.
add_subplot
(
221
)
ax1
.
plot
(
x_t
, f_list
[
0
], 'k-'
, label
=
'$f(x)$'
)
ax1
.
plot
(
x_t
, fa_list
[
0
], 'r--'
, label
=
'$f_a(x)$'
)
ax1
.
plot
(
x_inter_list
[
0
], f_inter_list
[
0
], 'bo'
, label
=
'$f(x_j)$'
)
ax1
.
set_xlabel
(
'$x$'
)
ax1
.
set_ylabel
(
''
)
ax1
.
set_ylim
(
-
1
, 1
)
ax1
.
set_title
(
'$n$ = 3'
)
ax1
.
legend
()
ax2 =
fig
.
add_subplot
(
222
)
ax2
.
plot
(
x_t
, f_list
[
1
], 'k-'
, label
=
'$f(x)$'
)
ax2
.
plot
(
x_t
, fa_list
[
1
], 'r--'
, label
=
'$f_a(x)$'
)
ax2
.
plot
(
x_inter_list
[
1
], f_inter_list
[
1
], 'bo'
, label
=
'$f(x_j)$'
)
ax2
.
set_xlabel
(
'$x$'
)
ax2
.
set_ylabel
(
''
)
ax2
.
set_ylim
(
-
1
, 1
)
ax2
.
set_title
(
'$n$ = 10'
)
ax2
.
legend
()
ax3 =
fig
.
add_subplot
(
223
)
ax3
.
plot
(
x_t
, f_list
[
2
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
2
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
2
], f_inter_list
[
2
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 20'
)
ax3
.
legend
()
ax3 =
fig
.
add_subplot
(
224
)
ax3
.
plot
(
x_t
, f_list
[
3
], 'k-'
, label
=
'$f(x)$'
)
ax3
.
plot
(
x_t
, fa_list
[
3
], 'r--'
, label
=
'$f_a(x)$'
)
ax3
.
plot
(
x_inter_list
[
3
], f_inter_list
[
3
], 'bo'
, label
=
'$f(x_j)$'
)
ax3
.
set_xlabel
(
'$x$'
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
---------------------------------------------------------------------------
IndexError
Traceback (most recent call last)
Cell In[111], line 46
44 # get monomial approximation for x_test
45 fa, f, err = approximate_monomial(c, x_t)
---> 46
fal, fl, errl = approximate_lagrange(c, x_interpolate, x_test)
48 # save data to lists
49 x_inter_list
.
append(x_interpolation)
Cell In[102], line 83
, in approximate_lagrange
(c, x_interpolate, x_test)
59 def
approximate_lagrange
(c, x_interpolate, x_test):
60 """Returns the interpolation error for a polynomial with a Lagrange basi
s.
61 62 This function assumes an f_true(x) function is globally available for cal
culating the true function value at x.
(...)
81 82 """
---> 83
fa
=
[lag(c,x,x_interpolate) for
x in
x_test]
84 # get f (vector of true function values for x_test)
85 f = np
.
array([f_true(x) for
x in
x_test])
Cell In[102], line 83
, in <listcomp>
(.0)
59 def
approximate_lagrange
(c, x_interpolate, x_test):
60 """Returns the interpolation error for a polynomial with a Lagrange basi
s.
61 62 This function assumes an f_true(x) function is globally available for cal
culating the true function value at x.
(...)
81 82 """
---> 83
fa
=
[lag(c,x,x_interpolate) for
x in
x_test]
84 # get f (vector of true function values for x_test)
85 f = np
.
array([f_true(x) for
x in
x_test])
Cell In[101], line 8
, in lag
(c, x, x_int)
6 for
i in
range
(n
+1
):
7 if
p
!=
i:
----> 8
poly *= (x
-
x_int[i])
9 poly /= (x_int[p]
-
x_int[i])
10 L
.
append(poly)
IndexError
: list index out of range
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 40'
)
ax3
.
legend
()
fig
.
savefig
(
'solution-figures/part1e-functions.png'
)
In [112…
a =
-
5
b =
5
x_t =
np
.
linspace
(
a
, b
, 1000
)
n_list =
np
.
array
([
5
, 10
, 20
])
# initialize lists for saving data
# initialize lists for saving data
fa_eq_list =
[]
fa_cheb_list =
[]
f_eq_list =
[]
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
f_cheb_list =
[]
e_eq_list =
[]
e_cheb_list =
[]
x_cheb_list =
[]
x_eq_list =
[]
# get data for each degree n
for
n in
n_list
:
# get equal and Chebyshev solutions
c_eq
, A_eq
, condition_eq
, x_eq =
solve_lagrange_equispaced
(
a
, b
, n
)
c_cheb
, A_cheb
, condition_cheb
, x_cheb =
solve_lagrange
(
a
, b
, n
)
# get monomial and Lagrange approximations for x_t
fa_eq
, f_eq
, err_eq =
approximate_lagrange
(
c_eq
, x_eq
, x_t
)
fa_cheb
, f_cheb
, err_cheb =
approximate_lagrange
(
c_cheb
, x_cheb
, x_t
)
# save data to lists
fa_eq_list
.
append
(
fa_eq
)
fa_cheb_list
.
append
(
fa_cheb
)
f_eq_list
.
append
(
f_eq
)
f_cheb_list
.
append
(
f_cheb
)
e_eq_list
.
append
(
err_eq
)
e_cheb_list
.
append
(
err_cheb
)
x_eq_list
.
append
(
x_eq
)
x_cheb_list
.
append
(
x_cheb
)
# plot interpolated and true functions
fig =
plt
.
figure
(
figsize
=
(
18
, 6
), tight_layout
=
True
)
plt
.
suptitle
(
t =
"Approximation of $1/(1+x^2)$ using Chebyshev and Equidistant Interpo
ax1 =
fig
.
add_subplot
(
131
)
ax1
.
plot
(
x_t
, f_cheb_list
[
0
], 'k-'
, label
=
'$f_{cheb}(x)$'
)
ax1
.
plot
(
x_t
, fa_cheb_list
[
0
], 'r--'
, label
=
'$f_{a, cheb}(x)$'
)
ax1
.
plot
(
x_t
, f_eq_list
[
0
], 'm-'
, label
=
'$f_{eq}(x)$'
)
ax1
.
plot
(
x_t
, fa_eq_list
[
0
], 'c--'
, label
=
'$f_{a, eq}(x)$'
)
ax1
.
set_xlabel
(
'$x$'
)
ax1
.
set_ylabel
(
''
)
ax1
.
set_title
(
'$n$ = 5'
)
ax1
.
legend
()
ax2 =
fig
.
add_subplot
(
132
)
ax2
.
plot
(
x_t
, f_cheb_list
[
1
], 'k-'
, label
=
'$f_{cheb}(x)$'
)
ax2
.
plot
(
x_t
, fa_cheb_list
[
1
], 'r--'
, label
=
'$f_{a, cheb}(x)$'
)
ax2
.
plot
(
x_t
, f_eq_list
[
1
], 'm-'
, label
=
'$f_{eq}(x)$'
)
ax2
.
plot
(
x_t
, fa_eq_list
[
1
], 'c--'
, label
=
'$f_{a, eq}(x))$'
)
ax2
.
set_xlabel
(
'$x$'
)
ax2
.
set_ylabel
(
''
)
ax2
.
set_title
(
'$n$ = 10'
)
ax2
.
legend
()
ax3 =
fig
.
add_subplot
(
133
)
ax3
.
plot
(
x_t
, f_cheb_list
[
2
], 'k-'
, label
=
'$f_{cheb}(x)$'
)
ax3
.
plot
(
x_t
, fa_cheb_list
[
2
], 'r--'
, label
=
'$f_{a, cheb}(x)$'
)
ax3
.
plot
(
x_t
, f_eq_list
[
2
], 'm-'
, label
=
'$f_{eq}(x)$'
)
ax3
.
plot
(
x_t
, fa_eq_list
[
2
], 'c--'
, label
=
'$f_{a, eq}(x)$'
)
ax3
.
set_xlabel
(
'$x$'
)
ax3
.
set_ylabel
(
''
)
ax3
.
set_title
(
'$n$ = 20'
)
ax3
.
legend
()
# plot error vs. n
fig =
plt
.
figure
(
figsize
=
(
8
,
3.75
), tight_layout
=
True
)
plt
.
suptitle
(
t =
"Error of Chebyshev and Equidistant Interpolation for $n = 5, 10, 20$
ax1 =
fig
.
add_subplot
(
121
)
ax1
.
plot
(
n_list
, e_cheb_list
, 'ko'
)
ax1
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax1
.
set_ylabel
(
'Error, $||e||$'
)
ax1
.
set_yscale
(
'log'
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
---------------------------------------------------------------------------
TypeError
Traceback (most recent call last)
Cell In[112], line 18
15 # get data for each degree n
16 for
n in
n_list:
17 # get equal and Chebyshev solutions
---> 18
c_eq, A_eq, condition_eq, x_eq = solve_lagrange_equispaced(a, b, n)
19 c_cheb, A_cheb, condition_cheb, x_cheb = solve_lagrange(a, b, n)
20 # get monomial and Lagrange approximations for x_t
Cell In[110], line 36
, in solve_lagrange_equispaced
(a, b, n)
33 A
=
np
.
identity(np
.
size(x_interpolate))
35 # get f (vector of true function values for interpolation points)
---> 36
f = [f_trued(x) for
x in
x_interpolate]
38 # solve matrix system
39 c = np
.
linalg
.
inv(A)
.
dot(f)
Cell In[110], line 36
, in <listcomp>
(.0)
33 A
=
np
.
identity(np
.
size(x_interpolate))
35 # get f (vector of true function values for interpolation points)
---> 36
f = [f_trued(x) for
x in
x_interpolate]
38 # solve matrix system
39 c = np
.
linalg
.
inv(A)
.
dot(f)
Cell In[109], line 21
, in f_trued
(x)
1 def
f_trued
(x):
2 """Returns the value of the true function at x.
3 4 Parameters
(...)
18 0.07067822452613834
19 """
---> 21
return
1/
(
1+
x
^2
)
TypeError
: ufunc 'bitwise_xor' not supported for the input types, and the inputs coul
d not be safely coerced to any supported types according to the casting rule ''safe''
ax2 =
fig
.
add_subplot
(
122
)
ax2
.
plot
(
n_list
, e_eq_list
, 'mo'
)
ax2
.
set_xlabel
(
'Polynomial Degree, $n$'
)
ax2
.
set_yscale
(
'log'
)
In [ ]:
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help