Can we define this piecewise function as a "simple function"?

4.3k Views Asked by At

Here is a piecewise function

$$f(x,y) = \begin{cases} 1-y(1-x), & \text{if $y > 0$} \\ \frac{1}{1+y(1-x)}, & \text{if $y < 0$} \\ 1, & \text{if $y = 0$} \end{cases}$$

I would like to express this same function without relying on checking in which range of values $y$ falls in?


For the simple case where $y$ could take only the values -1,1 and 0, then $f(x,y)=\left(1-y(1-x)\right)^y$ would work fine. This is as far as I could get.


Just for fun, below is a plot of this function for a given value of $x$:

### R code ###

f = function(x,y)
{
    if (y>0)
    {
        1-y*(1-x)
    } else{
        1/(1+y*(1-x))
    }
}

x=0.72
ys = seq(-2,2,0.01)
image=c()
for (y in ys) image[length(image)+1] = f(x=x,y=y)

plot(y=image,x=ys)

enter image description here


FYI, I am asking this question in the hope of fastening my C code by avoiding a potentially useless if statement.

3

There are 3 best solutions below

2
On BEST ANSWER

The time cost associated with the if statement is going to be less than any mathematical trick which turns it all into one equation. Any equation produced which would evaluate this appropriately in one line will end up involving more operations and more time than the single if statement. Also from a point of readability the way you have is better than a single equation.

If however this is for an assignment or something where you have to reduce it to one equation you could try the following:

$$\left(1-y(1-x)\right)\frac{1}{2}\left(\frac{|y|}{y}+1\right)+\left(\frac{1}{1+y(1-x)}\right)\frac{1}{2}\left(\frac{|y|}{y}-1\right)$$

This however will not work correctly for $y=0$.

A way to get around that and utilizing the symmetry of your two equations would be:

$$\left(1-|y|(1-x)\right)^{sgn(y)}$$

where $sgn(y)$ is the sign of $y$. Most programming languages have it.

Implementing it in Mathematica as:

With[{x = 0.72}, Plot[(1 - Abs[y] (1 - x))^Sign[y], {y, -2, 2}]]

gives me the graph:

enter image description here

1
On

You can usually recode "if" statements with crude tricks like this:

To write

$$ f(x) = x $$ if $x > 1$ but $$ f(x) = 1 $$ if $x < 1$, you can write (in Matlab, but I assume R is similar)

u = (x >= 0) .* x + (x < 0) .* 1;

Yeah, you end up computing both values and throwing one away. On the other hand, it's really easy to vectorize, etc.

3
On

In general if you have a function of the sort

$$f(x)= \begin{cases} g(x)\text{ for }x>0\\h(x)\text{ for }x<0 \end{cases}$$

it can be written as

$$ f(x)=\dfrac{1}{2}\left[ g(x)+h(x)+\dfrac{\vert x\vert}{x}(g(x)-h(x))\right]$$

but you would still have to handle the $0$ case.

I'm not familiar with R syntax but if it evaluates true statements a $1$ and false statements as $0$ then you could use something like

$$ f(x)=(x>0)\cdot g(x)+(x<0)\cdot h(x)+(x=0)\cdot 1$$