Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ; 
    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 ?

share|cite|improve this question
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
up vote 4 down vote accepted

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;
share|cite|improve this answer
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.

share|cite|improve this answer

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.

share|cite|improve this answer

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

share|cite|improve this answer

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

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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