Can't work out what I did wrong

1 view (last 30 days)
Tracy
Tracy on 3 Oct 2021
Answered: Tracy on 4 Oct 2021
I have obviously done something wrong with the f function I just dont know what. I apologise as this is most likely extreamly basic.
% compute the expressions f(x) and g(x)for x=10^-1,10^-2,...,10^-14
% which values (f(x) or g(x)is more accurate
x=[10^-(1),10^-(2),10^-(3),10^-(4),10^-(5),10^-(6),10^-(7),10^-(8),10^-(9),10^-(10),10^-(11),10^-(12),10^-(13),10^-(14)];
f=(exp(2.*x)-(exp(x).*cos(x)).^2./x.^2)
f = 1×14
1.0e+28 * -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0001 -0.0100 -1.0000
g=(exp(x).*sin(x)./x).^2
g = 1×14
1.2173 1.0202 1.0020 1.0002 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
% modify program to compute relative error in the inaccurate values using
% the more accurate values as estimates of the true value. For each
% x=10^-1, 10^-2,...,10^-14, print x, computed values and relative error
error_f=(f(x)-g(x)/g(x))
Array indices must be positive integers or logical values.
  2 Comments
DGM
DGM on 3 Oct 2021
Since we're comparing f against g for some measure of accuracy, we need to know what they're supposed to be. The fact that they're vastly different means that one or both of the expressions is incorrect, but there's no way to know which.
There are a couple additional things that can't hurt:
x = 10.^-(1:14); % a simpler way to write that
f = (exp(2.*x)-(exp(x).*cos(x)).^2./x.^2)
g = (exp(x).*sin(x)./x).^2
error_f = (f-g)./g % f and g are just numeric vectors
I'm not sure that's the intended way to calculate the error, but that looks like what you were trying to do.
Tracy
Tracy on 3 Oct 2021
This is the original question

Sign in to comment.

Accepted Answer

DGM
DGM on 3 Oct 2021
There were some parentheses misplaced in the expression for f. That said, the error is still large, but I suppose that's intentional due to what the question is asking.
x = 10.^-(1:14); % a simpler way to write that
f = (exp(2*x) - (exp(x).*cos(x)).^2)./x.^2 % parentheses on numerator
g = (exp(x).*sin(x)./x).^2
error_f = (f-g)./g % f and g are just numeric vectors

More Answers (2)

KSSV
KSSV on 3 Oct 2021
Replace the line
rror_f=(f(x)-g(x)/g(x)) ;
with
rror_f=(f-g./g) ;
f and g are already evaluated with the given values of x.
When you use f(x), g(x) as f, g are arrays, you are trying to index them with x which is not correct.

Tracy
Tracy on 4 Oct 2021
Thank you all so much for your help it is greatly appreciated.

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!