Mostly, it seems that using scalars and arithmetic operations with arrays and ranges gives me what I suspect. However, dividing a scalar by an array is not defined, whereas the elementwise version is (as opposed to other operators, where both versions work). And for ranges, it does work, but gives what seems to me to be the wrong answer, whether I use the elementwise version or not.
That is:
julia> [1, 2, 3] / 1
3-element Array{Float64,1}:
1.0
2.0
3.0
julia> 1 / [1, 2, 3]
ERROR: MethodError: no method matching /(::Int64, ::Array{Int64,1})
...
julia> 1 ./ [1, 2, 3]
3-element Array{Float64,1}:
1.0
0.5
0.333333
julia> 1 / 1:3
1.0:1.0:3.0
julia> 1 ./ 1:3
1.0:1.0:3.0
To clarify, my expectation would be that 1 / [1, 2, 3]
would yield the same result as 1 ./ [1, 2, 3]
, and that applying either /
or ./
to a range would yield the same result whether I used collect
before or after.
Are these expectations unfounded, or is this perhaps a bug (or simply some versions of the operators, with the range reverting to a default not intended for this purpose)?
Aaaaaah … I see my error wrt. the range, now. I guess it’s just a matter of precedence xD But the question about elementwise array division remains, I guess.
In v0.7 it returns some nonsense:
julia> 1/[1,2,3]
1Ă—3 Transpose{Float64,Array{Float64,1}}:
0.0714286 0.142857 0.214286
Opened an issue: https://github.com/JuliaLang/julia/issues/25431.
Edited: I was wrong, it is not nonsense, it is actually the pseudoinverse, see the issue for more details.
1 Like
Yes great question.
Elementwise operations on containers must use the elementwise (broadcasted) version like ./
and .+
etc.
We include array + array
(-
too) and scalar * array
(also division by scalar) only because these “whole container” operations make sense for vector spaces in linear algebra.
We’ve been deprecating all the other methods in favor of the “dot” version slowly over several revisions. One that slipped through was a buggy scalar / range
which has been deprecated in Julia v0.7.
It is not nonsense, but definitely surprising. I missed the original PR, so I guess it is too late to argue against this now. On the one hand I appreciate the mathematical elegance, OTOH this looks like something that can be invoked accidentally very easily (eg missing a .
in ./
, etc). It may be surprising to new users of the language who don’t expect this.
2 Likes
Exactly!
I can see this might be a logical consequence of treating scalars and 1x1 matrices as equivalents though. For example, when one wants to solve the system x^TA=b where A happens to be a single column vector (matrix) and b is therefore in this shady area of being a 1x1 matrix in some contexts and a scalar in others. In that case, right “dividing” by A on both sides might be a mathematically elegant way to get the solution for x. So there seems to be some rationale behind it but it’s rather subtle at first sight. Obviously, 1 element vectors are also in the same shady club.