[Python] Numpy's cosine and sine domains

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Numpy's trigonometric functions, and I just found something intriguing: I know that the sine and cosine functions have an infinite domain, but for some reasons np.cos() and np.sin() don't seem to.

    When I ask for angles out of [0, 2π], things start to get interesting:

    np.sin(0)
    Out[26]: 0.0

    np.sin(np.pi)
    Out[27]: 1.2246467991473532e-16

    np.sin(2 * np.pi)
    Out[28]: -2.4492935982947064e-16

    np.sin(3 * np.pi)
    Out[29]: 3.6739403974420594e-16

    np.sin(4 * np.pi)
    Out[30]: -4.898587196589413e-16

    np.sin(12000 * np.pi)
    Out[31]: -2.038010347584904e-12


    It goes similarly with the cosine function, and the bigger the input angle gets, the higher the error will be.

    np.sin(1e60*np.pi)
    Out[32]: 0.19270788453190046


    Now, I understand that a computer cannot perform high precision calculus when it comes to trigonometry, but is there a way to maintain this initial [0, 2π[ precision? Maybe some libraries that include a simple function like this:


    from numpy import pi

    # Just in order to keep it simple
    π = pi

    def sin(x):
    # If our angle is bigger than 360°
    if x >= 2*π:
    while x >= 2*π:
    x -= 2*π

    # If our angle is smaller than 0°
    elif x < 0:
    while x < 0:
    x += 2*π

    # If our angle is in [0, 2*π[ domain
    <act normally as Numpy>

    return result



    Is it something that wouldn't work, from a mathematical point of view? Why?

    Continue reading...

Compartilhe esta Página