I like to change the order of & programmatically. Is it possible? for example 3 < 4 & 1 < 4, & is evaluated first, but I like it be evaluated last.
You cannot change the precedence of & - precedence is resolved at parse time in Julia. Do either what Colin T Bowers suggested or use && which has a lower precedence than comparison operators.
Actually this is possible if you define an operator with lower precedence than & and give it the meaning of &.
julia> ↺(a,b) = a & b
↺ (generic function with 1 method)
julia> 3 < 4 ↺ 1 < 4
true
This is of course some kind of "cheating" and it will make writing other pieces of code with ↺ awkward because it has now the same precedence level as the => operator.
The list of available operators along with their precedence can be found at:
https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm
Related
I typed the following in Julia's REPL:
julia> 6÷2(1+2)
1
julia> 6÷2*(1+2)
9
Why are the different results output?
Presh Talwalkar says 9 is correct in the movie
6÷2(1+2) = ? Mathematician Explains The Correct Answer - YouTube
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.
I am looking for a mathematical expression to flip the sign of a number if two other numbers are positive.
This is easy for a single condition x > 0, in which case I'd do num *= sign(x).
But how to do that with two conditions x > 0 and y > 0? This is incorrect:
num *= sign(-x) * sign(-y)
(as it flips the sign also if both x < 0 and y < 0, which I don't want).
I'd come up with
num *= sgn(-x) ** H(y)
and
num *= 1 - 2 * H(x) * H(y)
where H is the Heavyside step function, but while that is brief, it's not explicit.
num *= (-1)^(H(x) * H(y))
is a bit better, but can we go nicer/shorter/more explicit?
This question is not specific to a particular programming language - actually, it's not about programming at all, so using an if is not exactly what I want. I am looking for something like an in-line if for mathematicians, and I thought I'd find people with the best mindsets for this question in a programmers' forum... please tell me I was right ;)
EDIT: As #MarkDickinson pointed out, you can use -sign(min(x, y)):
num *= -1 * sign(min(x, y))
Then:
If both are positive - the result is -1.
If at least one of them is negative - the result is 1.
You can use a ternary operator:
In mathematics, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A. The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison.
For example in C++ it would read:
num *= (x>0 && y>0) ? -1 : 1;
which represents (condition) ? if_true : if_false.
This would also work for the special case x and/or y evaluate to 0, since it would not flip the sign. Note sign(0) is usually defined as 0 and that is not the behaviour you said you wanted.
I saw in someone code that they were using the + operator as if it was a function by doing +(1,2,3). Is it possible to use operators as functions in Julia?
In addition, I also saw things like A ⊗ B, where the behaviour of ⊗ was customizable. How can I do such a thing, and is there a list of symbols I can use in this way?
Yes, you indeed can use operators as functions in Julia.
From the Julia Docs:
In Julia, most operators are just functions with support for special syntax. (The exceptions are operators with special evaluation semantics like && and ||. These operators cannot be functions since Short-Circuit Evaluation requires that their operands are not evaluated before evaluation of the operator.) Accordingly, you can also apply them using parenthesized argument lists, just as you would any other function:
julia> 1 + 3 + 5
9
julia> +(1,3,5)
9
julia> 1 * 3 * 5
15
julia> *(1,3,5)
15
julia> h = *;
julia> h(1,3,5)
15
In addition, Julia allows you to define your own meaning to operators, and makes quite a few symbols available for the purpose. You can find the list of available symbols here:|
https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm
and define them as such:
⊗(a, b) = a * 3 - b # or some other arbitrary thing
a ⊗ b == a * 3 - b # true
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?
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.
Suppose I have two custom infix operators in R: %foo% and %bar%.
I have expressions that use both operators, such as:
x %foo% y %bar% z
How can I determine the operator precedence of %foo% and %bar%?
How can I change the precedence so that, for example, %bar% always executes before %foo%? In the example above this would be the same as:
x %foo% (y %bar% z)
I don't think this is explicitly documented, but implicit in the R language documentation is that infix operators are all of equal precedence and so are executed from left to right. This can be demonstrated as follows:
`%foo%` <- `+`
`%bar%` <- `*`
1 %bar% 2 %foo% 3
#5
1 %foo% 2 %bar% 3
#9
The only option I can think of would be to redefine one of the existing operators to do what you wanted. However, that itself would have repercussions so you might want to limit it to within a function.
It's also worth noting that using substitute does not change the operator precedence already set when the expression is first written:
eval(substitute(2 + 2 * 3, list(`+` = `*`, `*` = `+`)))
#10
2 * 2 + 3
#7
How can I determine the operator precedence of %foo% and %bar%?
You can't. R doesn't allow you to set the precedence of custom infix operators. User-defined infix operators have the default precedence rules which means they will be evaluated from left to right.
One reason for this limitation is that it would be extremely difficult and limiting to implement and maintain a set of precendence rules for infix operators. Imagine that you loaded an R package which comes with some custom infix operators. Then the relationship of the infix operators from the package to the %foo% and %bar% which you created would need to be defined. This will quickly become a serious burden.
As an example, imagine that package one contains infix operator %P1IF% and package two contains infix operator %P2IF%. Each package has defined that its infix operator should have the highest precedence. If you were to load both package one and two, then the following expression would be undefined:
v1 %P1IF% v2 %P2IF% v3
(v1 %P1IF% v2) %P2IF% v3 # package 2 doesn't expect this
v1 %P1IF% (v2 %P2IF% v3) # package 1 doesn't expect this
Regardless of what the precedence might be the result for one of the two packages might be incorrect.