Can't work out what I did wrong
1 view (last 30 days)
Show older comments
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)
g=(exp(x).*sin(x)./x).^2
% 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))
2 Comments
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.
Accepted Answer
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
0 Comments
More Answers (2)
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.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!