Precision of Math.Cos() for a large integer

Viewed 597

I'm trying to compute the cosine of 4203708359 radians in C#:

var x = (double)4203708359;
var c = Math.Cos(x);

(4203708359 can be exactly represented in double precision.)

I'm getting

c = -0.57977754519440394

Windows' calculator gives

c = -0.579777545198813380788467070278

PHP's cos(double) function (which internally just uses cos(double) from the C standard library) on Linux gives:

c = -0.57977754519881

C's cos(double) function in a simple C program compiled with Visual Studio 2017 gives

c = -0.57977754519881342

Here is the definition of Math.cos() in C#: https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Math.cs#L57-L58

It appears to be a built-in function. I didn't dig (yet) in the C# compiler to check what this effectively compiles to but this is probably the next step.

In the meantime:

Why is the precision so poor in my C# example, and what can I do about it?

Is it simply that the cosine implementation in the C# compiler deals poorly with large integer inputs?

Edit 1: Wolfram Mathematica 11.0:

In[1] := N[Cos[4203708359], 50]
Out[1] := -0.57977754519881338078846707027800171954257546099993

Edit 2: I do need that level precision, and I'm ready to go pretty far in order to obtain it. I'd be happy to use an arbitrary precision library if there exists a good one that supports cosine (my efforts haven't led to one so far).

Edit 3: I posted the question on coreclr's issue tracker: https://github.com/dotnet/coreclr/issues/12737

3 Answers
Related