1
$\begingroup$

$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
    Yes Davis here has written a mathematical function here. However, oftentimes people think "function" means "formula" as in an equation (I think historians of mathematics believe that many respected authors thought of functions this way also... including Euler). So, Davis probably wants a formula like those referenced by lhf.2012-05-30

2 Answers 2

1

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.

  • 0
    In some languages you can also use the nice and short `bool ? iftrue : iffalse` construction, i.e. something like `return (x > 0) ? 1 : 0`.2012-05-30
0

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)$

  • 0
    I doubt it too. However he used the `interpolation` tag and was apparently trying to find another mathematical writting for his function.2012-05-30