0

I want to print the statement "They are equal" if the left side equation is equal to the right side equation for x=200. This is the equation. (sin(x) + cos(x))^2=1+2*(sin(x)*cos(x))

But when my program calculates the right side and left side equation, it does not execute the if statement even though the two sides are equal for x=200. This is my program:

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

I have tried debugging the program step by step and checked the values in memory after each step and nothing seems to be wrong.

values in memory

But the if statement still does not execute. Is there anything I am missing? Thank you for your help.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Yassine Hamadou
  • 191
  • 1
  • 4
  • Try removing the `;`'s you don't need them in Python and they can cause unexpected results. – Red Cricket Aug 15 '21 at 01:00
  • That's because they are not equal, just very close to each other. Try evaluating `left_side - right_side`, you'll notice it's not zero. – Florian Aug 15 '21 at 19:51

1 Answers1

1

What you're running into is a floating point rounding error. Here what you want to do is compare if the numbers are equal within a certain tolerance instead of directly equal; for example to 10 decimal places. Doing this should fix the code:

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

Also, since this was tagged with Python as well I thought I should throw in that as of Python3.5 the math module includes math.isclose() in case others come across this post.

BTables
  • 4,413
  • 2
  • 11
  • 30