6
$\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
  • 3
    $\begingroup$ And what if $b=0$? $\endgroup$
    – Henry
    Sep 7 '12 at 6:42
  • $\begingroup$ 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. $\endgroup$
    – Vishwas
    Sep 7 '12 at 10:57
6
$\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
  • 1
    $\begingroup$ How did you get the equation ?, a = 5/2 ( 5 b/|b| -3 ) ? Any logical approach ? $\endgroup$
    – Vishwas
    Sep 7 '12 at 14:27
  • $\begingroup$ Find $\alpha,\beta$ such that $a = \alpha \frac{b}{|b|}+\beta$. You have two conditions thus two equations with two variables. $\endgroup$
    – vanna
    Sep 7 '12 at 14:48
  • 1
    $\begingroup$ 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? $\endgroup$
    – Ultimater
    Dec 15 '15 at 2:37
5
$\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$
3
$\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$
1
$\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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.