为什么 Julia return 等价表达式的结果不同? 6÷2(1+2) 和 6÷2*(1+2)

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

我在 Julia 的 REPL 中输入了以下内容:

julia> 6÷2(1+2)
1

julia> 6÷2*(1+2)
9

为什么输出的结果不同?

Presh Talwalkar 说 9 在电影中是正确的 6÷2(1+2) = ? Mathematician Explains The Correct Answer - YouTube

尽管有 YouTube,但没有正确答案。您得到哪个答案取决于您用来解释问题的优先级约定。这些周期性传播的病毒式“谜语”中有许多之所以具有争议性,正是因为它们是故意模棱两可的。真的不是数学难题,这只是一个解析问题。不比某人说一句话有两种解释更深刻。在现实生活中,你会怎么做?你只要问他们指的是哪一个。这也不例外。正是出于这个原因,÷ 符号在真正的数学符号中并不经常使用——而是使用分数符号,这清楚地消除了它的歧义:

6
- (1 + 2) = 9
2

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

特别是关于 Julia,这里记录了这种优先行为:

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

具体来说:

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).

和注释:

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.