Hi @Brian,
Your task involves analyzing the accuracy of finite-difference approximations for the derivative of the function ( phi(x) = cos(2\pi x) ) on a one-dimensional uniform grid. Specifically, the goal is to compute and plot the ( L_1 ) and ( L_infinity ) error norms against the grid spacing, while determining the order of accuracy for both norms. The provided MATLAB code by you for the second-order accurate central-difference approximation is yielding unexpected results, prompting a review and correction of the code. So, after analyzing your comments and code, I made modifications to it which appears to address several key issues that may have contributed to the unexpected results in yours original implementation. Below, I will outline the primary improvements made in the modified code and how they contribute to resolving the issues you faced.
Key Improvements in the modified code
Initialization of Variables
The modified code now initializes Nj, delx, L1meannoper, and Linfnoper more clearly, establishing a structured approach to storing grid sizes and error norms. In contrast, your code use of nested loops made it less clear and potentially error-prone when referencing indices across different dimensions.
Grid Point Calculation
The calculation of grid points (xi ) is now more straightforward, directly using vectorized operations rather than nested loops. This minimizes potential indexing errors and enhances readability.
Derivative Approximation
The derivative approximation logic has been simplified. The central difference approximation is explicitly handled with clear conditions for boundary points, which reduces complexity and improves accuracy. Your code had a convoluted structure with unnecessary checks that could lead to indexing errors or incorrect calculations.
Error Calculation
The calculation of normalized errors (noperei) is clearer and uses absolute values directly, ensuring that negative discrepancies do not skew the results. L1 and L∞ norms are computed directly from the absolute values of errors, which enhances clarity and correctness.
Plotting
The plotting section is streamlined for better visualization, making it easier to interpret results. The use of markers in `loglog` plots helps identify data points clearly.
Here are some additional insights that I would like to share with you.
Expected Behavior of Error Norms: As grid spacing (Δx) decreases, one would typically expect both L1 and L∞ norms to decrease, indicating improved accuracy of the derivative approximation. If this behavior is not observed:
- Check for potential issues such as incorrect boundary conditions or incorrect calculations of derivative approximations.
- Make sure that the function being differentiated behaves well (i.e., is smooth) over the grid defined by `xi`.
Order of Accuracy: After obtaining the plots for L1 and L∞ norms against log(Δx), one can determine the order of accuracy by analyzing the slope of the log-log plots. A linear fit can provide insights into how quickly errors decrease as grid resolution increases.
Debugging Tips: If unexpected results persist:
- Print intermediate values (e.g., dynoper, noperei) for different iterations to trace where discrepancies arise.
- Compare outputs from both codes for specific values of `j` to pinpoint where differences occur.
Modified Code
Here is the revised MATLAB code that addresses the issues in the original implementation:
clear; clc; format long;
% Define the function and its derivative f = @(x) cos(2*pi*x); df = @(x) -2*pi*sin(2*pi*x);
% Initialize parameters max_j = 13; Nj = zeros(1, max_j); delx = zeros(1, max_j); L1meannoper = zeros(1, max_j); Linfnoper = zeros(1, max_j);
% Loop over j to create grids and compute errors for j = 1:max_j Nj(j) = 2^j + 1; % Number of grid points xi = (0:Nj(j)-1) / (Nj(j)-1); % Grid points delx(j) = 1 / (2^j); % Grid spacing y = f(xi); % Function values der = df(xi); % True derivative values
% Initialize the derivative approximation array dynoper = zeros(1, Nj(j));
% Central difference approximation (non-periodic) for k = 1:Nj(j) if k == 1 dynoper(k) = (y(k+1) - y(k)) / delx(j); % Forward difference elseif k == Nj(j) dynoper(k) = (y(k) - y(k-1)) / delx(j); % Backward difference else dynoper(k) = (y(k+1) - y(k-1)) / (2 * delx(j)); % Central difference end end
% Calculate the error noperei = (dynoper - der) / (2 * pi); % Normalized error
% Compute L1 and Linf norms L1meannoper(j) = sum(abs(noperei)) / Nj(j); % L1 norm Linfnoper(j) = max(abs(noperei)); % L∞ norm end
% Plotting the results figure; loglog(delx, L1meannoper, 'r-o'); xlabel('Log(Δx)'); ylabel('Log(L1 Norm)'); title('Log(L1 Norm) vs Log(Δx) assuming NO periodicity'); grid on;
figure; loglog(delx, Linfnoper, 'b-o'); xlabel('Log(Δx)'); ylabel('Log(L∞ Norm)'); title('Log(L∞ Norm) vs Log(Δx) assuming NO periodicity'); grid on;
% Display the results disp('Grid Spacing (Δx):'); disp(delx); disp('L1 Norms:'); disp(L1meannoper); disp('L∞ Norms:'); disp(Linfnoper);
Please see attached.
Explanation of the Code
Function Definitions: The function ( \phi(x) ) and its derivative are defined using anonymous functions for clarity and ease of use.
Grid Generation: The grid points ( x_i ) are generated based on the formula provided, ensuring that the spacing ( \Delta x ) is calculated correctly.
Finite-Difference Approximations: The code implements a second-order accurate central difference for interior points and first-order differences for the boundaries. This is crucial for accurately capturing the behavior of the derivative near the edges of the domain.
Error Calculation: The error is computed as the difference between the approximate derivative and the true derivative, normalized by ( 2\pi ) to match the problem statement.
Norm Calculation: The ( L_1 ) and ( L_\infty ) norms are calculated for each grid size, allowing for a comparison of accuracy as the grid is refined.
Plotting: The results are plotted on a logarithmic scale to visualize the relationship between the error norms and grid spacing, facilitating the determination of the order of accuracy.
This modified code should yield the expected results, with the error norms decreasing as the grid spacing decreases. The logarithmic plots will help in assessing the order of accuracy of the finite-difference approximations. If you have any further questions or need additional modifications, please feel free to ask.