I want to terminate my code when the approximate error is less than 4 significant digit. I couldn't solve it.

2 次查看(过去 30 天)
syms x k
f = sqrt(cos(x^2 + 1));
es = (0.5*10^(2-4));
ea = 1;
true_value = cos((0.2^2 + 1));
n = 1;
sum = 0;
sump = 0;
while ea > es
i = i+1;
for k= n:i+1
sump = taylor(f,x,'ExpansionPoint',0,'Order',n);
eps_t = abs((true_value-sump)/true_value);
ea = abs((sump-sum)/sump);
n = n+2;
sum = sump;
fprintf('\n %15.10f %5.1d %10.5f %10.5f\n',sump,sum,eps_t,ea);
  1 个评论
Geoff Hayes
Geoff Hayes 2022-3-30
@Alper Agaoglu - unfortunately I don't have the Symbolic Toolbox so cannot run your code. I do wonder about the following though
for k= n:i+1
sump = taylor(f,x,'ExpansionPoint',0,'Order',n);
eps_t = abs((true_value-sump)/true_value);
Why is sump overwritten on each iteration of the loop? Shouldn't it somehow reference what happenss on previous iterations of the loop? Also, what is the purpose of eps_t as I only see it used in the fprintf.
Finally, naming a variable sum is not good form since there is a MATLAB function of the same name. Please rename it to something else like taylorSum.


回答(1 个)

Dinesh 2023-9-18
Hi Alper!
I understand that you want to terminate the code execution once a certain condition is met. For the phrase 'Four significant digits' I assume that you are trying to say if the error is less than 0.00001 then you want to stop the execution.
This assumption is made as 999 has 3 significant digits but the error value is too high to terminate and 0.00000001111 has 4 significant digits but the error is very low to continue.
If this is the case then you can have a simple if condition check that will call 'return' when the condition is true.
But if you want the significant digits only then you can work as per the given code.
% counts the number of significant digits in number.
number = 0534.3245000;
%extract significant digits before the .
numberOfDecimals = numel(extractAfter(num2str(abs(number)), '.'));
%extract significant digits after the .
numberOfIntegers = numel(extractBefore(num2str(abs(number)), '.'));
numberOfFigures = numberOfIntegers + numberOfDecimals
numberOfFigures = 7
The problem with this approach is we have no way to make the trailing zeros in the decimal part be identified as significant. Because the number will have the value of 534.3245 stored in it.
Since you calculate the error in the loop and store it. We will not have a way to find the trailing zeros. If you would like to neglect them then you can use this approach to find the number of significant digits and then place an if condition to terminate the code.
For more details regarding the significant digits you may find the following MATLAB Answers thread useful
Hope this helps.
Best regards,
Dinesh Gatla.


Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by