Matlab 显示 x 的结果形式

Matlab shows result form of x

我正在尝试在 MATLAB 中编写修改后的牛顿公式,但 MATLAB 以符号 (x) 形式显示结果,而不是数字形式。这是代码:

clc
format long g
syms x;
fun = input ('Enter the function f(x)= : ','s');
f=inline(fun);
z=diff(f(x));
f1=inline(z);
z1=diff(f1(x));
f2=inline(z1);
u1=f(x)/f1(x);
u2=1-[(f(x)*f2(x))/(f1(x)^2)];
x0=input('enter the first guess x0=: ');
for i=0:6
    xn=x
    x=xn-[u1/u2];
    if x==xn
        break
    end
end

结果如下:

Enter the function f(x)= : x^2-2
enter the first guess x0=: 1

xn = 
x

xn =
x + (x^2 - 2)/(2*x*((2*x^2 - 4)/(4*x^2) - 1))

xn =
x + (x^2 - 2)/(x*((2*x^2 - 4)/(4*x^2) - 1))

xn =
x + (3*(x^2 - 2))/(2*x*((2*x^2 - 4)/(4*x^2) - 1))

xn =
x + (2*(x^2 - 2))/(x*((2*x^2 - 4)/(4*x^2) - 1))

xn =
x + (5*(x^2 - 2))/(2*x*((2*x^2 - 4)/(4*x^2) - 1))

xn =
x + (3*(x^2 - 2))/(x*((2*x^2 - 4)/(4*x^2) - 1))

我该如何解决? 谢谢

答案是符号变量,因为 x(并扩展为 xn)被定义为符号变量。要获得数值结果,请改用 subs:

for i=0:6
    xn=x;
    subs(xn) % display numerical value in the command window
    x=xn-[u1/u2];
    if abs(subs(x)-subs(xn))<=1e-6 % replace equality test by comparing difference to a small threshold value
        break
    end
end

注意:您不应该对浮点数进行相等性测试,而应该将差异与一个小阈值进行比较(参见我修改后的代码)。

是内联惹的祸。如果您打算使用类似的东西,您应该使用匿名函数,因为内联函数已被弃用并且即将被删除。但是,当使用符号时,这是完全多余的。这只会给你带来更多的麻烦,所以我强烈建议你摆脱内联。通常不建议使用 eval,但对于此应用程序来说应该没问题。我想还有其他方法可以做到这一点,但我觉得 eval 在评估表达式时感觉很直观。

此外,当您使用函数调用而不是输入时,您应该考虑一种方法。 function xout = newton(symbolicExpression, initialGuess)。这样更有活力。

下面的代码应该可以满足您的要求:

clc
format long g
syms x;
fun = input ('Enter the function f(x)= : ','s');
f = eval(fun);
f1 = diff(f);
f2 = diff(f1);
u1 = f/f1;
u2 = 1-( (f*f2)/(f1^2) );
x=input('enter the first guess x0=: ');
for i=0:6
    xn=x
    x=xn-eval(u1/u2);
    if (x-xn)<0.01
        break
    end
end