How can I convert a degrees angle to radians effectively in Python?

1.7k Views Asked by At

i'm writing a code in Python 3 to do some calculus with some parameters that user enters with keyboard.

When I was testing the program I faced and isolated the next problem:

Evaluating the angle in radians in a sin() function, converted from a degree angle entered by user, there is some trouble with the value, I suppose that is due to the decimals proximations in the operation.

Heres is the part of the code:

import math

degrees = int(input())

radians = degrees*(math.pi/180)

print(math.sin(radians))

So, most of the values you enter en degrees, seems ok, but when you enter 180º (Corresponds to PI and the resul must be 0), the output value is a very tiny value (1.2246467991473532e-16), but not 0.

3

There are 3 best solutions below

0
On

How about casting to round()?

import math
degrees = int(input("Enter the angle in degrees: "))
radians = degrees*(math.pi/180)
print(round(math.sin(radians)))

Which outputs 0 when you enter 180. But you are correct that it's going to round to the nearest integer no matter what.

math has math.radians() which will easily convert to radians, but won't cure your "false 0."I agree with the other commenter that you may need to set a threshold and anything below that prints 0.

import math
degrees = int(input("Enter the angle in degrees: "))
sin = math.sin(math.radians(degrees))
if -0.01 < sin < 0.01:
    print(0)
else:
    print("{:0.2f}".format(sin))
2
On

The value math.pi is a constant equal to 3.141592653589793. Obivously, it is not the same as the value pi because the decimals are infinite.

To fix that, you can round(value, 2) to get 2 decimals.

0
On

This is normal because you're dealing with floating point numbers and the nature of Pi certainly isn't helping. Does this actually cause a problem? which is to say does this tiny lack of accuracy cause problems in the code that is using this function? If you're only inputting integer degree values I doubt that it really is. You can likely ignore it. You can round your results using round (round(number,5) will round to 5 decimal places,) You can also hard code specific values that you need to be perfect and if you really want you could handle only values from 0 to 90 and then just play with signs to output the value you need. You will note that 0 and 90 return 0 and 1 respectively from math.sin.

Special values:

lookup = {180:0}
if degrees in lookup.keys(): return lookup[degrees]
else: do normal thing

if 180 is the only problem you can just use an if statement. exploiting the symmetry of sin is a bit more involved and likely round is going to meet your needs. using your code 180 and 360 are the only angles that don't return an exact value for the points that should return 0 and 1. you can get rid of the 360 problem by doing a modulus 360 degrees = degrees % 360 which will properly clamp your angles to between 0 and 359.