function testEstimateExp(estimateFun, lowerBound, upperBound, numSamplePoints) %function testEstimateExp(@estimateFun) % Helper function for APMA 4300 Homework Assignment #1 Call this function to % verify your estimateExp function, it will plot the Matlab exp function % against your estimateExp function, your absolute error at each point, and % display your average absolute error in ulps. % testEstimateExp(@estimateExp, lowerBound, upperBound, numSamplePoints) % allows you to customize lowerBound, upperBound, and numSamplePoints. % % estimateExp - function pointer to student estimateExp function % lowerBound - lower bound of linearly spaced sampling region % upperBound - upper bound of linearly spaced sampling region % numSamplePoints - number of points to sample in region DEFAULT_LOWER_BOUND = -20; DEFAULT_UPPER_BOUND = 20; DEFAULT_NUM_SAMPLE_POINTS = 20; % The below switch structure tests the MATLAB variable nargin, which is % set to the number of arguments the user called the current function % with. Type help switch or help nargin for more information on these. switch nargin case 1 lowerBound = DEFAULT_LOWER_BOUND; upperBound = DEFAULT_UPPER_BOUND; numSamplePoints = DEFAULT_NUM_SAMPLE_POINTS; case 4 otherwise error(['Wrong number of arguments to function. Type help' ... ' testEstimateExp for usage']); end % Create an array of evenly spaced points with linspace. xPoints = linspace(lowerBound, upperBound, numSamplePoints); % Now at each point, calculate the estimate and the true value, and use % Matlab's eps function to get the numerical value of the ulp at each % exp(x) % first - check for vectorized function try expEstimate = estimateFun(xPoints); expTrue = exp(xPoints); expUlp = eps(expTrue); catch for i=1:length(xPoints) expEstimate(i) = estimateFun(xPoints(i)); expTrue(i) = exp(xPoints(i)); expUlp(i) = eps(expTrue(i)); end end % Basic plotting figure; %clears figure subplot(2,1,1); %Sets up a 2 x 1 subplot and picks window 1 semilogy(xPoints, expEstimate, 'b--x'); %See help semilogy for info on this monster hold on; %Freezes plotting window semilogy(xPoints, expTrue, 'r-o'); legend('Student estimate', 'true','Location','NorthWest'); %See help legend title('Estimated versus true exp(x)'); xlabel('x'); ylabel('y'); grid; hold off; subplot(2,1,2); %Now selects window 2 of the 2 x 1 subplot absoluteErrorUlps = abs(expEstimate-expTrue)./expUlp; meanAbsoluteErrorUlps = mean(absoluteErrorUlps); plot(xPoints,absoluteErrorUlps, '.m-'); hold on %this needs to be a vector of values to draw a line plot(xPoints,ones(size(xPoints))*meanAbsoluteErrorUlps, 'r-'); legend('Absolute Error', 'Averaged Absolute Error','Location','NorthWest'); %A complicated title string like this requires me to build it first %using sprintf before I pass it to title titleString = sprintf('Absolute Averaged Error of Student Estimate (ulps): %d', ... meanAbsoluteErrorUlps); title(titleString); xlabel('x'); ylabel('error (ulps)'); grid; hold off