christiankral
christiankral

Reputation: 403

Override precedence of operator in Julia

In electrical engineering the parallel connection of impedances could be expressed by the parallel operator . For a vector of impedances z[k] the following function can be defined:

function ∥(z...)
    ypar = 0
    for k=1:length(z)
        ypar = ypar + 1/z[k]
    end
    return 1/ypar
end

The precedence of Julia operators is defined in https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm. The parallel operator is defined on the same precedence level as relational operators. Consider the following examples:

julia> Base.operator_precedence(:∥)
6
julia> Base.operator_precedence(:+)
9
julia> Base.operator_precedence(:*)
11
julia> Base.operator_precedence(:^)
13

In the simple case of two impedances z[1] and z[2] the parallel impedance is equal to z[1]*z[2]/(z[1]+z[2]). From my personal understanding the precedence of the parallel operator is higher or at least equal than the multiplication operator *.

My question is: how can I change the precedence of the operator from 6 to 11, 12 or 13?

Upvotes: 2

Views: 408

Answers (1)

Zulu
Zulu

Reputation: 111

I'll offer an answer you weren't looking for.

This impedance calculation is often referred to as a parallel sum, which I propose you represent with the ++ operator (two sums in parallel!). This could be defined in Julia as:

++(xs...) = 1/sum(1/x for x ∈ xs)

The precedence of ++ is the same as +. This seems undesirable at first, but I will argue that it is right.

The properties of the parallel sum—commutative, associative, and distributive—are exactly the same as addition, and the identities are just inverses of each other (0 vs. ∞). Both operators represent the addition of a component, just in different arrangements. And, just as the parallel sum can be defined in terms of the regular sum as a++b == 1/(1/a+1/b), the normal sum can be defined in terms of the parallel sum as a+b == 1/(1/a++1/b).

It turns out, it's most natural to give the parallel sum the same operator precedence as the normal sum. It's unfortunate that lots of electrical engineers give it precedence other than this—clearly because they haven't thought through the operator's properties.

Upvotes: 1

Related Questions