Sine

Hello,

The sine of 2*Pi = 0 but this peace of code:

Math.Sin(2 * Math.PI) gives: -2,44921270764475E-16

What is here wrong,

DIII




Answer this question

Sine

  • Adam_Machanic

    Hi DIII,

    The number -2,44921270764475E-16 in decimal format is equal to -0.0000000000000002449212707645, which for all practical purposes is zero. You can test the same by using following code

    class SinTest

    {

    public static void Main()

    {

    Console.WriteLine(Convert.ToDouble(Math.Sin(2 * Convert.ToDouble(Math.PI))));

    Console.WriteLine(Convert.ToDecimal(Math.Sin(2* Convert.ToDouble(Math.PI))));

    }

    }


  • jdtemp

    Oke,

    thanks for both answers.

    DIII



  • Spectre1337

    This is most probably becouse you are working with 2 floating point numbers, both of wich have an infinite amount of precision (infinite string of numbers after the decimal point) on a platform that has finite precision.

    The best way to fix this would be to create hardware and platforms that have infinite precision, but since that is impossible, (the last time I checked Pi has over 32000 known decimal places while the double type usually used for decimal number is 64 bits so it has a precision to about 16 digits), the other possible way would be to hardcode things like this into the compiler so it would always "produce" the correct result, but doing so can cause other calculations to become incorrect.

    So my advice is to know the limitations of the platform you are working with and work around them in the best way possible given the project you are working on at the time.

    Kjartan


  • Enselic

    Hi hedgeu,

    It isn't completly zero, but the code:

    Console.WriteLine(Convert.ToDecimal(Math.Sin(0.5 * Convert.ToDouble(Math.PI))));

    gives completly one, maybe the computer can't give the completly answer

    DIII



  • Sine