I want to create a step function $f(x,n)$ that works like this:
$n$ indicates the size of the interval and $x$ is the position in the $x$-axis.
I thought the following way:
- Let $k = x\div n$ (this maps the intervals to $[\dots,-4,-3,-2,-1,0,1,2,3,4,\dots]$).
- if $k \; mod \; 2 < 1$, return $1$, otherwise return $0$.
This works fine for non-negative numbers, but fails at negatives. How can I fix this function? Is there any better approach?

What you want in precise terms is $k=\lfloor x/n\rfloor$. Python's
//operator computes exactly that; in C and C++ you will need to importfloor().