根据真实值近似计算精确位数

Counting number of accurate digits in approximation against the true value

提问人:PattyWatty27 提问时间:9/19/2019 更新时间:9/19/2019 访问量:83

问:

我创建了执行牛顿方法近似的代码。它以类似表格的格式打印每个步骤的近似值和相关的误差。我想添加一列,该列显示一个整数值,该值表示与真实值的近似正确位数。

我正在尝试将每个近似单元格转换为字符串,并计算准确的位数。例如,大约 = 3.14555,true = 3.1555。准确位数为 2。虽然我脑子里有这个想法,但我在下面的代码中做错了。您知道如何创建适当的循环来实现这一点吗?我的 MATLAB 经验不到一年;我的思维工具箱是有限的。

% 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 
matlab for-loop if-statement char floating-accuracy

评论

3赞 David 9/19/2019
为什么不使用精确值和近似值之间的差异?请注意,.log10log10(abs(3.14555-3.1555))=-2.0022
0赞 PattyWatty27 9/19/2019
@David 这太聪明了!我将尝试。
0赞 PattyWatty27 9/19/2019
@David我认为这不会奏效。这应该是 0。>> log10(abs(0.32796778533175-0.263838689314425)) ans = -1.19294488198288
3赞 Ander Biguri 9/19/2019
@PattyWatty27它的 1,因为它们之间的数字差异小于 1。在您的情况下,您希望 0.19999 与 0.200001 为 0,但 0.19999 与 0.1 为 1?这不是很数学化(并且会让你感到困惑,特别是当你在做优化时。
0赞 PattyWatty27 9/20/2019
@AnderBiguri 这是真的。我没想过!也许我应该关注误差幅度。

答:

0赞 Jeremy Dorner 9/19/2019 #1

也许可以把两个数字乘以 10 的幂,然后把它们放在地板上,直到答案不再相等:

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;