Avoiding -0.0000 as an output

39 ビュー (過去 30 日間)
Left Terry
Left Terry 2025 年 2 月 3 日 10:49
編集済み: Left Terry 2025 年 2 月 3 日 14:26
Hello. I have the following script for differentiation and for some functions (e.g. f(x) = x) I get f'''(1) and f''''(1) equal to -0.0000. How can i avoid the minus sign when the reasult is zero ?
clear all, clc, format long e
f = @(x) x; %input('Enter f(x) = ');
x = 1; %input('Enter point: x = ');
tol = 1e-1; %input('Enter tolerance: ');
f3 = feval(f,x);
h = tol*f3;
f0 = feval(f,x-3*h);
f1 = feval(f,x-2*h);
f2 = feval(f,x-1*h);
f4 = feval(f,x+1*h);
f5 = feval(f,x+2*h);
f6 = feval(f,x+3*h);
d1f = (f1-8*f2+8*f4-f5)/12/h;
d2f = (-f1+16*f2-30*f3+16*f4-f5)/12/h^2;
d3f = (f0-8*f1+13*f2-13*f4+8*f5-f6)/8/h^3;
d4f = (-f0+12*f1-39*f2+56*f3-39*f4+12*f5-f6)/6/h^4;
p = [d1f;d2f;d3f;d4f];
fprintf('\nFirst derivative at x = %g:\tf''(%g) = %f\n',x,x,d1f);
First derivative at x = 1: f'(1) = 1.000000
fprintf('\nSecond derivative at x = %g:\tf''''(%g) = %f\n',x,x,d2f);
Second derivative at x = 1: f''(1) = 0.000000
fprintf('\nThird derivative at x = %g:\tf''''''(%g) = %f\n',x,x,d3f);
Third derivative at x = 1: f'''(1) = -0.000000
fprintf('\nFourth derivative at x = %g:\tf''''''''(%g) = %f\n',x,x,d4f);
Fourth derivative at x = 1: f''''(1) = -0.000000

採用された回答

Torsten
Torsten 2025 年 2 月 3 日 11:02
移動済み: Steven Lord 2025 年 2 月 3 日 14:08
The results for d2,...,d4 aren't exactly 0 because of floating point errors in their computation. So without artificially manipulating the results, you can't get rid of the minus sign.
  1 件のコメント
Left Terry
Left Terry 2025 年 2 月 3 日 11:19
編集済み: Left Terry 2025 年 2 月 3 日 14:26
@Torsten That is true, i just discovered what you said by making a small change. The results are extremely small and negative.
clear all, clc, format long e
f = @(x) x; %input('Enter f(x) = ');
x = 1; %input('Enter point: x = ');
tol = 1e-1; %input('Enter tolerance: ');
f3 = feval(f,x);
h = tol*f3;
f0 = feval(f,x-3*h);
f1 = feval(f,x-2*h);
f2 = feval(f,x-1*h);
f4 = feval(f,x+1*h);
f5 = feval(f,x+2*h);
f6 = feval(f,x+3*h);
d1f = (f1-8*f2+8*f4-f5)/12/h;
d2f = (-f1+16*f2-30*f3+16*f4-f5)/12/h^2;
d3f = (f0-8*f1+13*f2-13*f4+8*f5-f6)/8/h^3;
d4f = (-f0+12*f1-39*f2+56*f3-39*f4+12*f5-f6)/6/h^4;
p = [d1f;d2f;d3f;d4f];
fprintf('\nFirst derivative at x = %g:\tf''(%g) = %g\n',x,x,d1f);
First derivative at x = 1: f'(1) = 1
fprintf('\nSecond derivative at x = %g:\tf''''(%g) = %g\n',x,x,d2f);
Second derivative at x = 1: f''(1) = 2.40548e-14
fprintf('\nThird derivative at x = %g:\tf''''''(%g) = %g\n',x,x,d3f);
Third derivative at x = 1: f'''(1) = -1.38778e-13
fprintf('\nFourth derivative at x = %g:\tf''''''''(%g) = %g\n',x,x,d4f);
Fourth derivative at x = 1: f''''(1) = -1.07322e-11

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by