TITLE: Why do different calculators disagree on $\cos(452175521116192774 )$?
QUESTION [23 upvotes]: I want to calculate cosine of 452175521116192774 radians (it is around $4.52\cdot10^{17}$)
Here is what different calculators say:
Wolframalpha 
Desmos

Geogebra

Python 3.9 (standard math module)

Python 3.9 (mpmath library)

Obviously there is only one solution. There could be errors in floating point precision for these calculators, but this stumbles me. My calculator (TI-30XIS) says domain error (which is weird because cosine of, for example, a billion works just fine). How can I get the cosine of very large integers?

REPLY [4 votes]: As Hans Lundmark pointed out, the problem is caused by converting the argument to a C double before doing the calculation.
But if you don't want to bring in a high-precision math library, there's a way (at least in Python) to calculate a more accurate value by using the sum-of-angles identities.
from math import cos, sin

def cossin(x):
    '''
    Return (cos(x), sin(x)) more accurately.
    '''
    if abs(x) < 2 ** 53:
        # All integers below this threshold are represented exactly,
        # so just use the normal math module functions.
        return (cos(x), sin(x))
    else:
        a = float(x)
        b = x - int(a)  # the approximation error
        # a is a float, so use the normal math functions.
        cos_a = cos(a)
        sin_a = sin(a)
        # for b, call recursively in case *it* can't be represented as float
        cos_b, sin_b = cossin(b)
        return (cos_a * cos_b - sin_a * sin_b, cos_a * sin_b + sin_a * cos_b)

This agrees pretty closely with WolframAlpha's result.
>>> cossin(452175521116192774)
(-0.5229034783961185, -0.8523919006426797)


An alternative approach is to use a high-precision approximation of π to reduce the argument modulo 2π.  (In Python, you can use the Fraction class to store your approximation.  This gives you:
$$452175521116192774 \approx 71965969330795778 \times 2\pi + 4.162135302888925$$
And taking the cosine of the reduced argument will give you the correct result.
>>> cos(4.162135302888925)
-0.5229034783961188