# Converting an IF condition to a mathematical equation

I am trying to study about converting algorithms into mathematical equations. For this I just started with a simple random example :

function set_b( int b):int
{
if ( b >= 0)
{
a = 5 ;
}
else
if ( b < 0 )
{
a = -20
}

}


By looking at the above algorithm, one can say :

a is dependent upon b. So : a = f(b). Also, the two blocks of Ifs are actually talking about -ve and +ve number lines.

But after this i get stuck, where to start approaching the solution from. Some equation like

a = b + blah blah - blah blah * blah blah etc.

Any clues or hints pls ?

-
And what if $b=0$? – Henry Sep 7 '12 at 6:42
ok, b < 0 is now b <= 0 . Actually it's not important what equality it has. What i wanna focus on is how to solve such if conditions mathematically. – Vishwas G Sep 7 '12 at 10:57

Try $$a = \frac{5}{2}\left( 5 \frac{b}{|b|} - 3 \right)$$ If you just want to shorten your code, I suggest using the ternary operator like (C++ style)

int set_b(int b) {
int a = (b<0)?-20:5;
return a;
};

-
How did you get the equation ?, a = 5/2 ( 5 b/|b| -3 ) ? Any logical approach ? – Vishwas G Sep 7 '12 at 14:27
Find $\alpha,\beta$ such that $a = \alpha \frac{b}{|b|}+\beta$. You have two conditions thus two equations with two variables. – vanna Sep 7 '12 at 14:48
But what if b=0? Then the b/abs(b) logic for getting the sign fails. Is there a way to adjust the equation to account for 0? – Ultimater Dec 15 '15 at 2:37

Hint: try using the function $b / |b|$ (which is $1$ for $b > 0$, -1 for $b< 0$), as a building block, and then applying a couple elementary transforms (vertical dilation and translation) to get what you want.

-

One way could be:

$$a = f(b) = \begin{cases} 5& b < 0\\-20& b > 0\end{cases}$$

Do you see something that could help this? What about the $b = 0$ case.

Can you see how to also define it using the Heaviside Unit Step function as an alternate solution?

Sorry that I have not yet learned the TeX style to make this look proper.

-
a=5*(b>0)-20*(b<0)


A bit redundant since the two conditions on the same variable (b) are mutually exclusive, but it works.

-

let $a=f(b)$ ;then code says that for all $b>=0$ ,$a=5$ and for all input $b<0$,$a=-20$,this is if we consider into mathematical term,likely piecewise function

-