What mathematical function would do this: if $x = 0$ then $y = 0$ but if $x > 0$ then $y = 1$?

2k Views Asked by At

$x = 0$, $f(x) = 0$

$x = 1$, $f(x) = 1$

$x = 2$, $f(x) = 1$

$x = 3$, $f(x) = 1$

...

There have been so many times I could have used this at different programming problems but I always resorted to logical expressions. I feel that there should be a more elegant, purely mathematical, solution.

2

There are 2 best solutions below

5
On

Unfortunately, checking my typical python and java packages (the only languages I work in now), I exception handle NaN cases. So my original post wouldn't work unless you also handle them.

If you're looking for a good way to code this, then you might try either

if x > 0: return 1
return 0

or, if you're in a language which evaluates True to 1, False to 0, something like

return int(x>0)

But in terms of a mathematical function, your description alone is a mathematical function. There is no ambiguity about $f:[0,\infty] \to \mathbb{R}$, $f(x) = 0$ if $x = 0$, and $f(x) = 1$ else.

2
On

Apparently you described the sign function. However, if your problem is to interpolate points, you can use Lagrange polynomials. Given abscissae $(x_1,...,x_n)$ with corresponding ordinates $(y_1,...,y_n)$, the Lagrange polynomial $$L(X) = \sum_{i=1}^n y_i l_i(X)$$ with $$l_i(X) = \prod_{j=1,j\neq i}^n \frac{X-x_j}{x_i-x_j}$$ satisfies $\forall i =1,..,n$ $L(x_i)=y_i$. Such polynomial is unique, given the latter set of abscisase and ordinates.

In your example with points $(0,0), (1,1), (2,1), (3,1)$ this leads to $$L(X) = X\left(\frac{1}{6}X^2 - X + \frac{11}{6}\right)$$