# Very simple math code gives me wrong answer

Hi, I’m just beginning my programming journey (as of this morning) an I’m starting off with a very simple code to convert degrees to radians and vice versa with Python 3.10. I really cannot figure out what the problem is. The code works fine but I get a slight difference between the expected answer and what my code gives me.

The first part of my code gives me the result 1.4884264823743867 radians, when the expected answer is 1.4863757205032933 radians.

Using the result obtained in the first part of the code in the second part to convert back to degrees, minutes and seconds should give me back my original input, but it’s not the case. I get 85°16’50’’ instead of 85°9’47’'. What am I doing wrong?

Here’s my code:

from math import pi, floor
#Convert degrees to radians

angle_deg = 85
angle_min = 9
angle_sec = 47
angle_rad = (angle_deg + angle_min / 60 + angle_sec / 360) * pi / 180

#Convert radians too degrees

angle_deg2 = floor(angle_rad2 * 180 / pi)
angle_min2 = floor(angle_rad2 * 180 / pi % 1 * 60)
angle_sec2 = floor(angle_rad2 * 180 / pi % 1 * 60 % 1 * 60)

print(angle_deg2, angle_min2, angle_sec2)

The calculation isn’t wrong, unfortunately, your math is. What you want is:

``````angle_rad = (angle_deg + angle_min / 60 + angle_sec / 3600) * pi / 180
``````

Notice we are dividing seconds by `3600`, not `360`.

Thanks a lot! I was too focused on the code obviously…

No problem, it happens to the best of us. Sometimes we are too close to our problem to see the real issue.

1 Like

To simplify your code a bit, you could use `math.degrees()`/`math.radians()` - they convert (decimal) degrees to/from radians for you, so you don’t have to manually specify the `π/180` factor. You might want to look into using `divmod()` also, which computes both the floor division and modulus. That way you don’t need to repeat yourself as much.

By Spencer Brown via Discussions on Python.org at 21Aug2022 22:39:

To simplify your code a bit, you could use
`math.degrees()`/`math.radians()` - they convert (decimal) degrees
to/from radians for you, so you don’t have to manually specify the
`π/180` factor. You might want to look into using `divmod()` also,
which computes both the floor division and modulus. That way you don’t
need to repeat yourself as much.

For someone just starting out in programming, writing the arithmetic is
often the purpose, to learn to express these things in code and to learn
to debug.

Cheers,
Cameron Simpson cs@cskk.id.au