step function working only for non negative numbers

198 Views Asked by At

I want to create a step function $f(x,n)$ that works like this:

enter image description here

$n$ indicates the size of the interval and $x$ is the position in the $x$-axis.

I thought the following way:

  1. Let $k = x\div n$ (this maps the intervals to $[\dots,-4,-3,-2,-1,0,1,2,3,4,\dots]$).
  2. 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?

1

There are 1 best solutions below

2
On

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 import floor().