-1

I have faced a really weird problem. when I want to find sin or cos of some angles, I get strange answers in python interpreter.

>>>from math import *
>>>sin(pi)
Out:1.2246467991473532e-16
>>>cos(pi)
Out:-1.0

It answered cos correctly but sin was strange. while pi/2 is reverse.

>>>sin(pi/2)
Out: 1.0
cos(pi/2)
Out: 6.123233995736766e-17

I'm confused!

Can someone explain what's happening?

BTW I use canopy and python 2.7.9

Ali Tohidi
  • 73
  • 7
  • at least you won't have division by zero issues ;) sorry for the joke, i guess the reason is that you should use tau – Kaddath Jul 20 '17 at 12:39
  • 1
    For all intents and purposes, those values are zero. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – roganjosh Jul 20 '17 at 12:39
  • Please go through this https://en.wikipedia.org/wiki/Propagation_of_uncertainty – Akhil Mathew Jul 20 '17 at 12:41
  • Welcome to the world of finite precision arithmetic. When using floating-point, never expect the computations to be exact (sometimes they are "by accident"). Anyway, in most cases the results have a much better accuracy than the data you provide. (Who can measure an angle with less than 10^{-16} error ? This is a must-read: "What Every Computer Scientist Should Know About Floating-Point Arithmetic". –  Jul 20 '17 at 13:23

1 Answers1

1

I think the output to the following will answer your question. Your output isn't wrong, it's just the side effect of using computers for calculations.

print "sin(pi) = %.2f\ncos(pi/2) = %.2f" % (sin(pi), cos(pi/2))
Sam Chats
  • 2,271
  • 1
  • 12
  • 34