[Python] Why does math.cos(math.pi/2) not return zero?

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I came across some weird behavior by math.cos() (Python 3.11.0):

    >>> import math
    >>> math.cos(math.pi) # expected to get -1
    -1.0
    >>> math.cos(math.pi/2) # expected to get 0
    6.123233995736766e-17


    I suspect that floating point math might play a role in this, but I'm not sure how. And if it did, I'd assume Python just checks if the parameter equaled math.pi/2 to begin with.

    I found this answer by Jon Skeet, who said:


    Basically, you shouldn't expect binary floating point operations to be exactly right when your inputs can't be expressed as exact binary values - which pi/2 can't, given that it's irrational.
    ​

    But if this is true, then math.cos(math.pi) shouldn't work either, because it also uses the math.pi approximation. My question is: why does this issue only show up when math.pi/2 is used?

    Continue reading...

Compartilhe esta Página