#   3: y = 1./(1+25*x.^2).
#   4: y = sqrt(abs(x))

## Functions to be approximated
funcs = [
    lambda x: 1 + x + 2 * x**2 - 3 * x**3, lambda x: np.exp(-x), lambda x: 1 /
    (1 + 25 * x**2), lambda x: np.sqrt(np.abs(x))
]

# Set degree of approximation and endpoints of approximation interval
n = 7  # degree of approximation
a = -1  # left endpoint
b = 1  # right endpoint

# Construct uniform grid for error ploting
x = nodeunif(2001, a, b)


def subfig(k, x, y, xlim, ylim, title):
    plt.subplot(2, 2, k)
    plt.plot(x, y)
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.title(title)


for ifunc, ff in enumerate(funcs):

    # Construct interpolants
    C = BasisChebyshev(n, a, b, f=ff)
    S = BasisSpline(n, a, b, f=ff)
示例#2
0
y1 = 1 + 3 * x
y2 = 1 + 3 * x + 8 * x**2

plt.figure(figsize=[6, 6])
plt.plot(x, y, 'k', linewidth=3, label='Function')
plt.plot(x, y1, 'b', linewidth=3, label='1st order approximation')
plt.plot(x, y2, 'r', linewidth=3, label='2nd order approximation')
plt.legend()
plt.xticks([-1, 0, 1])
plt.show()

## Bivariate Taylor approximation
nplot = [101, 101]
a = [0, -1]
b = [2, 1]
x1, x2 = nodeunif(nplot, a, b)
x1.shape = nplot
x2.shape = nplot

y = np.exp(x2) * x1**2
y1 = 2 * x1 - x2 - 1
y2 = x1**2 - 2 * x1 * x2 + 0.5 * x2**2 + x2


def newPlot(title, Y, k):
    ax = fig.add_subplot(1, 3, k, projection='3d')
    ax.plot_surface(x1,
                    x2,
                    Y,
                    rstride=1,
                    cstride=1,
示例#3
0
ax2 = fig.add_subplot(122, title='Derivative approximation error', **axopts)
ax2.plot(x, np.zeros_like(x), '--', color='gray', linewidth=2)
ax2.plot(f1fit.nodes, np.zeros_like(f1fit.nodes), 'ro', markersize=12)
ax2.plot(x, f1fit(x, 1) - d1(x))
''' Bivariate Interpolation '''
# Define function
f2 = lambda x: np.cos(x[0]) / np.exp(x[1])

# Set degree and domain interpolation
n, a, b = 7, 0.0, 1.0
f2fit = BasisChebyshev([n, n], a, b, f=f2)

# Nice plot of function approximation error
nplot = [101, 101]
x = nodeunif(nplot, a, b)
x1, x2 = x
error = f2fit(x) - f2(x)
error.shape = nplot
x1.shape = nplot
x2.shape = nplot

fig = plt.figure(figsize=[15, 6])
ax = fig.gca(projection='3d',
             title='Chebyshev Approximation Error',
             xlabel='$x_1$',
             ylabel='$x_2$',
             zlabel='Error')
ax.plot_surface(x1,
                x2,
                error,
示例#4
0
    'The exact and approximate second partial derivatives of f w.r.t. x1 at x=[0 0] is'
)
print('{:4.0f}  {:20.15f}\n'.format(0, d11))
print(
    'The exact and approximate second partial derivatives of f w.r.t. x2 at x=[0 0] is'
)
print('{:4.0f}  {:20.15f}\n'.format(0, d22))
print(
    'The exact and approximate second cross partial derivatives of f at x=[0 0] is'
)
print('{:4.0f}  {:20.15f}\n'.format(-1, d12))

# One may evaluate the accuracy of the Chebychev polynomial approximant by computing the approximation error on a
# highly refined grid of points:
nplot = [101, 101]  # chose grid discretization
X = nodeunif(nplot, [a, a], [b, b])  # generate refined grid for plotting
yapp = F(X)  # approximant values at grid nodes
yact = f(X)  # actual function values at grid points
error = (yapp - yact).reshape(nplot)
X1, X2 = X
X1.shape = nplot
X2.shape = nplot

fig = plt.figure(figsize=[15, 6])
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(X1,
                X2,
                error,
                rstride=1,
                cstride=1,
                cmap=cm.coolwarm,
y1 = 1 + 3 * x
y2 = 1 + 3 * x + 8 * x ** 2

plt.figure(figsize=[6, 6])
plt.plot(x, y, 'k', linewidth=3, label='Function')
plt.plot(x, y1, 'b', linewidth=3, label='1st order approximation')
plt.plot(x, y2, 'r', linewidth=3, label='2nd order approximation')
plt.legend()
plt.xticks([-1, 0, 1])
plt.show()

## Bivariate Taylor approximation
nplot = [101, 101]
a = [0, -1]
b = [2, 1]
x1, x2 = nodeunif(nplot, a, b)
x1.shape = nplot
x2.shape = nplot

y = np.exp(x2) * x1 ** 2
y1 = 2 * x1 - x2 - 1
y2 = x1 ** 2 - 2 * x1 * x2 + 0.5 * x2 ** 2 + x2

def newPlot(title, Y, k):
    ax = fig.add_subplot(1, 3, k, projection='3d')
    ax.plot_surface(x1, x2, Y, rstride=1, cstride=1, cmap=cm.coolwarm,
                    linewidth=0, antialiased=False)
    ax.set_xlabel('$x_1$')
    ax.set_ylabel('$x_2$')
    ax.set_zlabel('$y$')
    plt.title(title)
ax2.plot(x, np.zeros_like(x), '--', color='gray', linewidth=2)
ax2.plot(f1fit.nodes, np.zeros_like(f1fit.nodes), 'ro', markersize=12)
ax2.plot(x, f1fit(x, 1) - d1(x))


''' Bivariate Interpolation '''
# Define function
f2 = lambda x: np.cos(x[0]) / np.exp(x[1])

# Set degree and domain interpolation
n, a, b = 7, 0.0, 1.0
f2fit = BasisChebyshev([n, n], a, b, f=f2)

# Nice plot of function approximation error
nplot = [101, 101]
x = nodeunif(nplot, a, b)
x1, x2 = x
error = f2fit(x) - f2(x)
error.shape = nplot
x1.shape = nplot
x2.shape = nplot

fig = plt.figure(figsize=[15, 6])
ax = fig.gca(projection='3d', title='Chebyshev Approximation Error',
             xlabel='$x_1$', ylabel='$x_2$', zlabel='Error')
ax.plot_surface(x1, x2, error, rstride=1, cstride=1, cmap=cm.coolwarm,
                linewidth=0, antialiased=False)
plt.show()

# Compute partial Derivatives
x = np.array([[0.5], [0.5]])
示例#7
0
# Function to be  approximated


def f(x):
    g = np.zeros((3, x.size))
    g[0], g[1], g[2] = np.exp(-x), -np.exp(-x), np.exp(-x)
    return g


# Set degree of approximation and endpoints of approximation interval
a = -1  # left endpoint
b = 1  # right endpoint
n = 10  # order of interpolatioin

# Construct refined uniform grid for error ploting
x = nodeunif(1001, a, b)

# Compute actual and fitted values on grid
y, d, s = f(x)  # actual

# Construct and evaluate Chebychev interpolant
C = BasisChebyshev(n, a, b, f=f)  # chose basis functions
yc = C(x)  # values
dc = C(x, 1)  # first derivative
sc = C(x, 2)  # second derivative

# Construct and evaluate cubic spline interpolant
S = BasisSpline(n, a, b, f=f)  # chose basis functions
ys = S(x)  # values
ds = S(x, 1)  # first derivative
ss = S(x, 2)  # second derivative
# Function to be  approximated


def f(x):
    g = np.zeros((3, x.size))
    g[0], g[1], g[2] = np.exp(-x), -np.exp(-x), np.exp(-x)
    return g

# Set degree of approximation and endpoints of approximation interval
a =  -1                            # left endpoint
b =   1                            # right endpoint
n =  10                            # order of interpolatioin

# Construct refined uniform grid for error ploting
x = nodeunif(1001, a, b)

# Compute actual and fitted values on grid
y, d, s = f(x)                     # actual

# Construct and evaluate Chebychev interpolant
C = BasisChebyshev(n, a, b, f=f)    # chose basis functions
yc = C(x)                           # values
dc = C(x, 1)                        # first derivative
sc = C(x, 2)                        # second derivative


# Construct and evaluate cubic spline interpolant
S = BasisSpline(n, a, b, f=f)       # chose basis functions
ys = S(x)                           # values
ds = S(x, 1)                        # first derivative
#   3: y = 1./(1+25*x.^2).
#   4: y = sqrt(abs(x))

## Functions to be approximated
funcs = [lambda x: 1 + x + 2 * x ** 2 - 3 * x ** 3,
         lambda x: np.exp(-x),
         lambda x: 1 / ( 1 + 25 * x ** 2),
         lambda x: np.sqrt(np.abs(x))]

# Set degree of approximation and endpoints of approximation interval
n = 7   # degree of approximation
a = -1  # left endpoint
b = 1   # right endpoint

# Construct uniform grid for error ploting
x = nodeunif(2001, a, b)

def subfig(k, x, y, xlim, ylim, title):
    plt.subplot(2, 2, k)
    plt.plot(x, y)
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.title(title)

for ifunc, ff in enumerate(funcs):

    # Construct interpolants
    C = BasisChebyshev(n, a, b, f=ff)
    S = BasisSpline(n, a, b, f=ff)
    L = BasisSpline(n, a, b, k=1, f=ff)