Matlab:以最小迭代次数,精确到小数点后的结果

Matlab:以最小迭代次数,精确到小数点后的结果,matlab,precision,numerical-methods,decimal-point,Matlab,Precision,Numerical Methods,Decimal Point,我用数值积分法来近似积分。我需要使用一个最小的迭代次数,给出一个精确到小数点后5位的答案 我似乎找不到一个通用的方法来做这件事。我只能在某些情况下使用它 以下是我尝试过的: %num2str(x,7) to truncate the value of x xStr = num2str(x(n),7); x5dp(n) = str2double(xStr); %convert back to a truncated number %find the difference between the

我用数值积分法来近似积分。我需要使用一个最小的迭代次数,给出一个精确到小数点后5位的答案

我似乎找不到一个通用的方法来做这件事。我只能在某些情况下使用它

以下是我尝试过的:

%num2str(x,7) to truncate the value of x
xStr = num2str(x(n),7);
x5dp(n) = str2double(xStr); %convert back to a truncated number

%find the difference between the values
if n>1  %cannot index n-1 = 0
check = x5dp(n)-x5dp(n-1);   
end
这将找到第一个实例,在该实例中,第一个5dp是相同的,它没有考虑到在该点之后可能发生的变化,这已经发生了,我正在寻找的迭代大约是450次,但由于这个原因,它在178次停止

然后我试了这个

while err>errLim & n<1000
    ...
    r = fix(x(j)*1e6)/1e1    %to move the 6th dp to the 1stplace
    x6dp = rem(r,1)*10    %to 'isolate' the value of the 6th dp
    err = abs(x(j)-x(j-1))  % calculate the difference between the two

    %if the 6th decimal place is greater than 5 and err<1e-6
    % then the 6th decimal place won't change the value of the 5th any more
    if err<errLim && x6dp<5    
       err=1;
    end
    ...
 end

while err>errLim&n除了用
num2str
转换数字外,你还可以使用
round(x,5)
将数字四舍五入为5位。注意,我后来将其改为round的一种变体(因为我只能访问round(x),round(x,n)只有在2014a之后,我相信。实际上我使用num2str/str/str2时,我认为它并没有四舍五入(我只想要前5位数字,例如4.39053,而不考虑第6个dp。事实证明并非如此。@用户7813820,在2014b之前,您可以使用正常公式将其舍入到给定精度:
round2precision=@(x,prec)round(x*10^prec)/10^prec;
。这允许您将十进制数四舍五入到所需的精确位数。