Search code examples
matlabfor-loopif-statementcharfloating-accuracy

Counting number of accurate digits in approximation against the true value


I have created code that does a Newton's Method approximation. It prints in a table-like format the approximation at each step and the associated error. I want to add a column that shows an integer value that represents the number of correct digits in approximation against the true value.

I am attempting to convert each cell of approximation into a string and counting how many digits are accurate. Example, approx. = 3.14555, true = 3.1555. The number of accurate digits will be 2. Although I have this idea in my head, I am doing it all wrong in my code below. Do you know how to create a proper loop to achieve this? I have less than a year of MATLAB experience; my mental toolbox is limited.

% Program Code of Newton's Method to find root
% This program will not produce a result if initial guess is too far from
% true value
clear;clc;format('long','g')
% Can work for various functions
%FUNCTION: 2*x*log(x)-2*log(x)*x^(3)+2*x^(2)*log(x)-x^(2)+1
%INTIAL GUESS: .01
%ERROR: 1.e-8
a=input('Enter the function in the form of variable x:','s');
x(1)=input('Enter Initial Guess:');
error=input('Enter allowed Error:');
% Passing through the function and calculating the derivative
f=inline(a);
dif=diff(str2sym(a));
d=inline(dif);
% Looping through Newton's Method
for i=1:100
x(i+1)=x(i)-((f(x(i))/d(x(i))));
err(i)=abs(x(i+1)-x(i));
% The loop is broken if acceptable error magnitude is reached 
if err(i)<error
break
end
end
root=x(i);
Root = (x(:,1:(end-1)))';
Error = err';

disp('The final approximation is:')
disp(root)
%BELOW IS ALL WRONG, I AM TRYING TO ADD A COLUMN TO 'table' 
%THAT SHOWS HOW MANY DIGITS IN APPROXIMATION IS ACCURATE
iter = 0;
y = zeros(1,length(x)); 
plot(x,y,'+')
zero1 = ('0.327967785331818'); %ACTUAL VALUE
for i = 1:length(Root)
    chr = mat2str(Root(i))
    for j = 1:length(chr(i))
        if chr(i)~=zero1(i)
            iter = 0;
            return
        elseif chr(i)==zero1(i)
            iter = iter + 1;
            acc(i) = iter
        end

    end

end
table(Root, Error)   %ADD ACCURACY COLUMN HERE 

Solution

  • Perhaps something like multiplying both numbers by powers of 10 and then flooring them until the answers are no longer equal:

    approx=3.14555;
    truth=3.1555;
    approx1=0;
    truth1=0;
    i=0;
    while approx1==truth1
       approx1=floor(approx*10^i);
       truth1=floor(truth*10^i);
       i=i+1;
    end
    acc=i-1;