How to work around the precision problem?
이전 댓글 표시
I am aware that certain numbers cannot be perfectly represented in binary, and as a result some of the numbers are not exact.
I am trying to calculate the numerical derivative of x^4 + 3x^3 - 2x^2 + x - 2
n = 10001;
lb = 0;
ub = 2;
dx = (ub-lb)/(n-1);
t = 1:n;
x = t*dx - dx;
u0 = x.^4+3*x.^3-2*x.^2+x-2;
figure;
hold on;
plot(x,u0);
drawnow;
u = u0;
ntemp = n;
ntempstart = 1;
for i = 1:4
du_dx = dudx(u,dx,length(ntempstart:ntemp));
ntempstart = ntempstart+1;
ntemp = ntemp - 1;
plot(x(ntempstart:ntemp),du_dx);
drawnow;
u = du_dx;
end
function du_dx = dudx(u,dx,n)
du_dx = zeros(1,n-2);
for i = 2:n-1
du_dx(i-1) = (u(i+1) - u(i-1))/(2*dx);
end
end
This is a debugging process for a numerical solution of the KdV equation and I am asked to solve the derivatives in KdV using derivative definition such as the one defined here. I am trying to get to the bottom of this:
When I run the above code with n = 1001 or smaller number of increments, it produces the expected derivative results. But when I increase it to 10001 as shown, I get the following. I believe the problem is caused by the precision limitations. Is the only solution to not use such a high number of increments? I tried to round the values for the third and fourth derivative, but they do not help. Rounding for all cases makes it worse.

댓글 수: 2
Walter Roberson
2020년 3월 29일
x = t*dx - dx;
would be more precise as
x = (t-1)*dx;
Zhangxi Feng
2020년 3월 29일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Fortran with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


