Steven - 1 year ago 64
Java Question

# Converting an If-Else statement into a Formula

I have code as follows:

```````if (a <= 10){
z = 5;
} else {
z = -1;
}`
``````

I figured out that when
`s(10 - a) = |10 - a| / (10 - a)`
where it outputs a 1 or -1. It outputs
`1`
if
`a < 10`
and
`-1`
if
`a > 10`
.

Then, I just solve the linear equation
`z = s(10 - a) * m + b`
, to find constants m and b.

`5 = 1 * m + b`
and
`-1 = -1 * m + b`

Which outputs
`b = 2, m = 3`
.

Then this can be modeled as
`z = 3 * s(10 - a) + 2`
.

Now the question becomes more tricky. What if I have two variables in nested if statements? Such as:

```````if (a <= 10){
if(b <= 3){
z = 3;
} else {
z = 1;
}
} else {
if(b <= -5){
z = -11;
} else {
z = 4;
}
}`
``````

I tried to solve this using another series of linear equations.

1. `3 = A * s(10 - a) + B * s(3 - b) + C`

2. `1 = A * s(10 - a) + B * s(3 - b) + C`

3. `-11 = A * s(10 - a) + D * s(-5 - b) + C`

4. `4 = A * s(10 - a) + D * s(-5 - b) + C`

with A, B, C, D as constants. However, this isn't giving me the right answer. What am I doing wrong?

An if statement can be transformed into a formula by using the following trick: we need to find a formula that's 1 if the `if` statement is true and 0 otherwise. We can use the signum function for this:
`````` f(x, y) = (sign(y - x) + 1) / 2
``````f(a, 10) * (f(b, 3) * 3 + g(b, 3) * 1) + g(a, 10) * (f(b, -5) * -11 + g(b, -5) * 4)