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);
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
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.