uo-ec607 / lectures

Lecture notes for EC 607
MIT License
1.5k stars 616 forks source link

Fix improper logical operators #19

Closed nk027 closed 3 years ago

nk027 commented 4 years ago

I stumbled upon an issue in the introduction to logical operators. Two examples are 1 > 2 | 0.5, and 1 > 2 & 0.5. These evaluate to TRUE and FALSE, with the implication being that 1 is indeed greater than 2 or 0.5, but not than 2 and 0.5. However, this is not what happens in the code. Instead, due to operator precedence and type conversion R evaluates the first statement as:

    1 > 2 | 0.5
    FALSE | 0.5
    FALSE | TRUE
    TRUE

And the second statement as:

    1 > 2 & 0.5
    FALSE & 0.5
    FALSE & TRUE
    FALSE

To verify this you can run e.g.:

    5 > 2 & 10 # TRUE
    5 > 10 & 2 # FALSE
    5 < 2 | 10 # TRUE

I have adapted the examples to work properly (1 > 2 | 1 > 0.5) and added a comment on operator precedence.

grantmcdermott commented 3 years ago

Quite right. Easier to see if you switch the order, i.e. 1 > 0.5 & 2 evaluates to TRUE.

Thanks!