CS代写 function condNumExpt(funcode,x)

function condNumExpt(funcode,x)
% compute and display the condition number of a function f at an input x,
% and determine whether the log10 of the condition number approximately
% tells us how many digits of accuracy we lose in evaluating f at x.

Copyright By PowCoder代写 加微信 powcoder

% Since we don’t know the true answer, we use single precision for the
% computation, and compare the result with the double precision answer,
% which serves as a very good approximation to the true answer. So, the
% Rule of Thumb tells us that number of digits of accuracy is approximately
% **** 7 minus the log10 of the condition number ****
% funcode = 1: exp
% funcode = 2: log
% funcode = 3: sine
if funcode == 1
f = @(x) exp(x);
fprime = @(x) exp(x);
elseif funcode == 2
f = @(x) log(x); % natural log, base e
fprime = @(x) 1/x;
elseif funcode == 3
f = @(x) sin(x);
fprime = @(x) cos(x);
% evaluate f, its derivative and its condition number at x
fx = f(x); % called y in the notes
fprimex = fprime(x); % derivative
condx = abs(fprimex*x/fx); % the condition number of at x
% round x from the default double precision to single
xS = single(x); % round x to single precision
if xS == x
error(‘xS and x are exactly the same. try again’)
% evaluate f at the rounded single precision value of x
% **** since xS is a single, f(xS) is also returned as a single ****
fxS = f(xS); % fxS is what we call yhat in the notes
% relative error in fxS, taking fx as the exact value
relerr = abs((fxS – fx)/fx); % |yhat – y|/|y| in notes
% approximate number of digits they are in agreement
digits = max([-log10(relerr), 0]); % makes no sense to talk about negative correct digits
% log base 10 of condition number
log10cond = log10(condx);
fprintf(‘fx = %20.15e\n’,fx) % y
fprintf(‘fxS = %20.15e\n’,fxS) % yhat
fprintf(‘condnum is %g\n’,condx)
fprintf(‘num of accurate digits is approx %g, log10 cond of f at x is %g\n’,digits,log10cond)

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com