Why does Julia return different results for equivalent expressions? 6÷2(1+2) and 6÷2*(1+2)

Viewed 124
1 Answers

YouTube notwithstanding, there is no correct answer. Which answer you get depends on what precedence convention you use to interpret the problem. Many of these viral "riddles" that go around periodically are contentious precisely because they are intentionally ambiguous. Not a math puzzle really, it's just a parsing problem. It's no deeper than someone saying a sentence with two interpretations. What do you do in that case in real life? You just ask which one they meant. This is no different. For this very reason, the ÷ symbol isn't often used in real mathematical notation—fraction notation is used instead, which clearly disambiguates this as either:

6
- (1 + 2) = 9
2

or as

    6
--------- = 1
2 (1 + 2)

Regarding Julia specifically, this precedence behavior is documented here:

https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#man-numeric-literal-coefficients

Specifically:

The precedence of numeric literal coefficients is slightly lower than that of unary operators such as negation. So -2x is parsed as (-2) * x and √2x is parsed as (√2) * x. However, numeric literal coefficients parse similarly to unary operators when combined with exponentiation. For example 2^3x is parsed as 2^(3x), and 2x^3 is parsed as 2*(x^3).

and the note:

The precedence of numeric literal coefficients used for implicit multiplication is higher than other binary operators such as multiplication (*), and division (/, \, and //). This means, for example, that 1 / 2im equals -0.5im and 6 // 2(2 + 1) equals 1 // 1.

Related