3
$\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 ?

  • 0
    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.2012-09-07

4 Answers 4

5

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; }; 
  • 1
    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?2015-12-15
4

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.

2

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.

1

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