-1

My Problem is that I don't get the same calculations on python, than on my calculator:

Calculations on Calculator in Degree mode:

cos(270)

that gives me:

0

When I put the same calculations in python:

print(math.cos(math.radians(270)))

I get something completely different:

-1.8369701987210297e-16

I guess it is a very simple Mistake I made, please help me....

Paul
  • 1,349
  • 1
  • 14
  • 26
  • 4
    It is just a rounding error. The value you are getting of `-1.8369701987210297e-16` is extremely close to 0 and can just be interpreted as that way. – JamieT Apr 17 '19 at 23:52
  • 1
    To be clear, that `e-16` is short for "multiplied by 10 to the power of negative 16", a very small number (15 zeroes after the decimal point). – Blorgbeard Apr 17 '19 at 23:54
  • 3
    Seems like another variation of the much duplicated [is floating point math broken?](https://stackoverflow.com/q/588004/4996248) – John Coleman Apr 17 '19 at 23:55

1 Answers1

2

Like is described in the comments, this is just a rounding error. -1.8369701987210297e-16 is extremely close to 0 and can be viewed as such.

If you want a number such as your expected behavior, round the result as so using round(value, decimalplaces). Let's round to 2 decimal spots:

>>> print('cos(270) is', round(math.cos(math.radians(270)), 2))
cos(270) is -0.0
wjandrea
  • 28,235
  • 9
  • 60
  • 81
JamieT
  • 1,177
  • 1
  • 9
  • 19
  • BTW, about the `-0.0`: [negative zero in python](https://stackoverflow.com/q/4083401/4518341) – wjandrea Apr 18 '19 at 00:31
  • To be even more clear, the rounding error is on cos input already, you can not represent pi with a finite number of bits after floating point... – aka.nice Apr 20 '19 at 07:27