Is there a math expression equivalent to the conditional ternary operator?

Is there a math equivalent of the ternary conditional operator as used in programming?

a = b + (c > 0 ? 1 : 2)

The above means that if c is greater than 0 then a=b+1, otherwise a=b+2.

Answer

From physics, I’m used to seeing the Kronecker delta,δij{1ifi=j0else,and I think people who work with it find the slightly generalized notationδ[condition]{1if[condition]0elseto be pretty natural to them.

So, I tend to use δ[condition] for a lot of things. Just seems so simple and well-understood.

Transforms:

  1. Basic Kronecker delta:
    To write the basic Kronecker delta in terms of the generalized Kronecker delta, it’s justδijδi=j.It’s almost the same notation, and I think most folks can figure it out pretty easily without needing it explained.

  2. Conditional operator:
    The “conditional operator” or “ternary operator” for the simple case of ?1:0:if (condition){    return 1;}else{    return 0;}  condition ? 1 : 0 δ[condition].Then if you want a non-zero value for the false-case, you’d just add another Kronecker delta, δNOT([condition]), e.g. δij.

  3. Indicator function:
    @SiongThyeGoh’s answer recommended using indicator function notation. I’d rewrite their example likea=b+1+1(,0](c)their examplea=b+1+δc(,0]direct translationa=b+1+δc0cleaner form.

  4. Iverson bracket:
    Iverson bracket notation, as suggested in @FredH’s answer, is very similar to the generalized Kronekcer delta. For example:δi=j    [i=j].Dropping the “ \delta “ reduces backwards-compatibility withe the basic Kroncker delta, plus it weakens the signal about what the notation means, so it’s probably not as good in general contexts right now. However, Iverson bracket notation should be easier to read and write, so when reinforcing the meaning of the notation isn’t a big issue, it could be preferable.


Note: “Conditional operator” rather than “ternary operator“.

The conditional operator, condition ? trueValue : falseValue, has 3 arguments, making it an example of a ternary operator. By contrast, most other operators in programming tend to be unary operators (which have 1 argument) or binary operators (which have 2 arguments).

Since the conditional operator is fairly unique in being a ternary operator, it’s often been called “the ternary operator“, leading many to believe that that’s its name. However, “conditional operator” is more specific and should generally be preferred.

Attribution
Source : Link , Question Author : dataphile , Answer Author : Community

Leave a Comment