提问人:PattyWatty27 提问时间:9/19/2019 更新时间:9/19/2019 访问量:83
根据真实值近似计算精确位数
Counting number of accurate digits in approximation against the true value
问:
我创建了执行牛顿方法近似的代码。它以类似表格的格式打印每个步骤的近似值和相关的误差。我想添加一列,该列显示一个整数值,该值表示与真实值的近似正确位数。
我正在尝试将每个近似单元格转换为字符串,并计算准确的位数。例如,大约 = 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
答:
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;
上一个:在matlab中加速程序
下一个:1 的分数之和不完全等于 1
评论
log10
log10(abs(3.14555-3.1555))=-2.0022
>> log10(abs(0.32796778533175-0.263838689314425)) ans = -1.19294488198288