How can I check that if 90, 270, 450 etc. are present?

I was working on a terminal-based scientific calculator. I knew that when I type cos(90) on it, it will brings up a rounding bug. May I ask that if there is any way to get the cosine value is 90, 270, 450 etc?

My Code Here:

if 'cos(' in expression:
    temp = float(expression.split('cos(')[-1].split(')')[0]) #the number
    expression = re.sub(r"cos\(([0-9]+\b)\)", str(math.cos(math.radians(float(expression.split('cos(')[-1].split(')')[0])))), expression) #It returns a rounding bug

Solution 1:

Use the modulus operator to check for this.

if temp % 180 == 90:
    # do something about rounding bug
else:
    # handle it normally

Solution 2:

I hate special cases. When you need a special case but kinda think you shouldn't, there's usually something going on that would suggest another way to go. In this case, there isn't a bug, either in the language or in your code. Rather, it's a precision issue, since 90 * Pi can't be represented perfectly with floating point. So you're getting the right answer for the code, but that answer is not what you would like to see.

So what do you want to see in general? Better to handle a problem generally than with a special case. Well, generally, I expect that you don't care about the value of your result out to 16 or so decimal places, right? So instead of having a special case, just tell the code how much precision you really care about, like this:

import math

desired_precision = 6

print(round(math.cos(math.radians(90)), desired_precision))
print(round(math.cos(math.radians(180)), desired_precision))
print(round(math.cos(math.radians(23)), desired_precision))

You'll then get answers you expect, now that you've told the code more precisely what you want:

0.0
-1.0
0.920505

It's a general rule that's good to follow that whenever you print a floating point value, you run it through round. In addition to fixing the more objectional issue addressed by this question, it also avoids values being displayed with an excessive number of decimal places and/or in exponential notation, often not what you want even for numbers with a meaningful fractional component.

PS: 180 degrees is also not perfectly representable in radians with floating point, but you don't see that in an unrounded answer because the rounding that has to occur happens to go your way in that case.