1
$\begingroup$

I don't know if this is the right stackexchange for this question, please tell me/move it if it isn't.

I calculate a value $x$ that can be any integer number. I now want to use this variable to get a factor thats $0$ if $x$ is zero, and 1 if it isn't.

I can easily program this with an if-statement, however due to optimization reasons, I want to get around the if. So I was wondering if there is a mathematical expression that would give me $fac = 1$ if $x\ne0$ and $fac=0$ if $x = 0$.

$\endgroup$
2
$\begingroup$

You can set a new variable equal to the floor of $x/(x-1)$. ( as long as $x$ can't be equal to $1$). Alternatively the ceiling of $x/(x+1)$ (as long as $x$ isn't negative).

$\endgroup$
  • $\begingroup$ In theory good, but if $x=1$, I have an integer division by zero, which is not good. using $x$ as a floating point number and calculating the floor, gives me for $x=1$ $fac=-2147483684.000$ (I think that's not a math problem but a programming problem). $\endgroup$ – Fl.pf. Nov 23 '18 at 11:10
  • $\begingroup$ @Fl.pf. My bad, you could do the ceiling of $x/(x+1)$ as long as $x$ can't be negative. $\endgroup$ – CooperCape Nov 23 '18 at 11:14
  • $\begingroup$ I'm having the same problems with the ceiling function as with the floor function. Pretty weird that floor and ceiling give me the same result. That shouldn't happen, right? $\endgroup$ – Fl.pf. Nov 23 '18 at 11:26
  • $\begingroup$ @Fl.pf. That is rather bizarre. $\lceil\frac{x}{x+1}\rceil\equiv 1\ \forall\ x\in\mathbb{Z}^+$ $\endgroup$ – CooperCape Nov 23 '18 at 11:32
  • $\begingroup$ it is. But I think this is now purely programming weirdness and your solution is still right, so I'll figure that out somehow. Thank you for your time :) $\endgroup$ – Fl.pf. Nov 23 '18 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.