我的 MATLAB 程序没有执行 IF 语句。我正在计算 x=200 等式左右两边的值

My MATLAB program is not executing the IF STATEMENT. I'm calculating the values of the left and right sides of the equation for x=200

如果 x=200 的左侧方程等于右侧方程,我想打印语句“它们相等”。这就是等式。

但是当我的程序计算方程式的右边和左边时,它不执行 if 语句,即使 x=200 的两边相等。 这是我的程序:

clear, clc

x = 200;
left_side = (sin(x) + cos(x))^2;
right_side = 1+2*(sin(x)*cos(x));

if right_side == left_side
    disp('they are equal')
end

我试过一步一步调试程序,每一步都检查内存中的值,似乎没有错。

但是if语句还是没有执行。我有什么想念的吗? 谢谢你的帮助。

您 运行 遇到的是浮点舍入错误。这里你要做的是比较数字是否在一定的公差范围内相等,而不是直接相等;例如到小数点后 10 位。这样做应该可以修复代码:

clear, clc

x = 200;

left_side = (sin(x) + cos(x))^2;
right_side = 1+2*(sin(x)*cos(x));
tolerence = 1e-10;
if abs(left_side - right_side) < tolerance
    disp('they are equal')
end

此外,由于这也被标记为 Python,我想我应该在 Python3.5 中加入它,数学模块包括 math.isclose() 以防其他人遇到这个 post.