Representing IF ... THEN ... ELSE ... in math notation

58.7k Views Asked by At

How do I correctly represent the following pseudocode in math notation?

EDIT1: Formula expanded. EDIT2: Clarification.

(a,b) represents a line segment on a 1D line. a <= b for each segment. The division show below is done as per the following T-SQL code (which I suppose could be represented as a function in the formula?):

Input: @a1 real, @b1 real, @an real, @bn real

DECLARE @Result real

if @a1 <= @an begin
    SET @Result = @an - @b1

    if @Result <= 0 RETURN 0

    RETURN @Result / @an
end

SET @Result = @a1 - @bn

if @Result <= 0 RETURN 0

RETURN @Result / @a1

Formula:

if m = 1 then
  if (a,b)_1 intersects (a,b)_n then
    r = 1
  else if (a,b)_1 < (a,b)_n then
    r = (a,b)_1 / (a,b)_n
  else
    r = (a,b)_n / (a,b)_1
else if m = 2 then
  if (a,b)_1 intersects (a,b)_n then
    r = 1
  else if (a,b)_1 < (a,b)_n then
    r = (a,b)_1 / (a,b)_n
  else
    r = (a,b)_n / (a,b)_1

The m = 2 block is shown as being the same as the m = 1 one for simplicity's sake.

The divisions are against the two points that are closets to each other, unless the segments intersect, at which point r = 1.

4

There are 4 best solutions below

9
On BEST ANSWER

In general, if you have "If $\varphi$ then $\psi$, otherwise $\tau$" you can write this as the following formula (or sentence, depending on $\varphi,\psi,\tau$):

$\left(\varphi\rightarrow\psi\right)\wedge\left(\neg\varphi\rightarrow\tau\right)$

If you have several cases, you can either nest them (i.e. $\tau$ would be "if second condition then, else ...") or if you can express them as $\varphi_1$ meaning only the first case holds, and none of the others as $(\varphi_1\rightarrow\psi_1)\wedge(\varphi_2\rightarrow\psi_2)\wedge\ldots$

Addendum:

$(a=b\rightarrow x=1)\wedge(a<b\rightarrow x=\frac{a}{b})\wedge(a>b\rightarrow x=\frac{b}{a})$

I have added $x$ as a variable, because writing just $\rightarrow 1$ seems very meaningless to me, you can of course replace $x$ by anything you'd like. The idea, essentially is that you express "IF ... THEN ... ELSE" structures using the $\rightarrow$ (or $\implies$ sometimes) and I gave you in my original post the method of doing so.

3
On

Or just $\begin{cases} a & b \\ c & d \end{cases}$

0
On

You could potentially convert it to a mathematical formula too.

For example say we had the following:

if (a < b) then c = 100 
else if (a > b) then c = 200
else c = 300.

This can be rewritten as

$$c = 300 \ (1 - \text{sgn}^2(a-b)) + \text{sgn}^2(a-b)(50 \ \text{sgn}(a-b) + 150)$$

Where $\text{sgn}(x)$ is the sign of $x$, as defined here; http://en.wikipedia.org/wiki/Sign_function.

(It is defined as: 1 for positive, 0 for 0, and -1 for negative)

0
On

How to implement If-then-else structures in propositional logic:

Example 1

If P then
  Q
else
  R
end if

(P -> Q) & (~P -> R)

Example 2

If P then
  Q
else if R then
  S
else
  T
end if

(P -> Q) & (~P & R -> S) & (~P & ~R -> T)