M HYPE SPLASH
// news

Converting an IF condition to a mathematical equation

By John Campbell
$\begingroup$

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 ?

$\endgroup$ 2

4 Answers

$\begingroup$

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;
};
$\endgroup$ 3 $\begingroup$

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.

$\endgroup$ $\begingroup$

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.

$\endgroup$ $\begingroup$

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

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy