[Math] Can we define this piecewise function as a “simple function”

functionspiecewise-continuityproblem solving

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.

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

Related Question