1

I am trying to calculate sin(pi radians) using Math.Sin(). I am using the following code.

        double degrees = 180;
        double radians = Math.PI / 180 * degrees;
        Console.WriteLine(Math.Sin(radians));

It is giving me a value of

1.22460635382238E-16

What is the reason for this? Surely it should be returning a value of 0 right?

Please enlighten me. Thanks.

user1727141
  • 133
  • 2
  • 11
  • 1
    For all "Is ... wrong?" -- No, your use of it or your expectations are wrong ;-) –  Mar 03 '13 at 13:32
  • Your angle is technically speaking not exactly pi, it's just some approximation (as pi has infinitely many significant decimal digits). Why is it a problem to get an approximation of 0 as a result? – Vlad Mar 03 '13 at 13:48
  • It's not a problem, I was just curious as to why it wasn't returning exactly 0, since sin(pi radians) in Google calculator and calc.exe was giving me 0 I assumed Math.Sin() would be the same. Thanks for the answers. – user1727141 Mar 03 '13 at 13:53
  • 1
    Do you expect Math.PI to be *precisely pi* with an infinite number of decimal places, or do you expect it to be pi rounded off to about fifteen decimal places? Since pi is wrong in the fifteenth decimal place, the result is also wrong in the fifteenth decimal place. – Eric Lippert Mar 03 '13 at 15:57
  • No of course not, I just expected it to give me the same value that the said calculators were giving. Maybe it should round the value down to 0? – user1727141 Mar 04 '13 at 01:08
  • Wolfram Alpha [gets it right if you say PI](http://www.wolframalpha.com/input/?i=sin%28pi%29), and gets about the same number [if you only provide 15 digits of PI](http://www.wolframalpha.com/input/?i=sin%283.141592653589793%29), which verifies @EricLippert comment. – doug65536 Sep 26 '16 at 02:47

1 Answers1

8

1.22460635382238E-16 basically is 0. it actually represents the number

0.000000000000000122460635382238. This number is close to 0. It's basically just because of different rounding errors all coming together.

take a look at http://en.wikipedia.org/wiki/Floating_point for more information.

Immortal Blue
  • 1,691
  • 13
  • 27