Calculate an interval on a scale / axis that allways has a point / gridline at $0$

2.5k Views Asked by At

I have an axis with a defined start (min) and end (max) value.

  • $min <= 0$
  • $max > 0$.

Now i want to have 15 to 20 identical magnitude sections with one hitting the point zero.

To demonstrate the problem I have this picture: variable x-scala Only the X-axis is of interest.

So I am looking for an formula to calculate the interval size between min and max to always hit the point $0$ with a gridline (the values of min and max can be changed within the given limits).

The min and max is can be rounded to a number divisible by 10 without remainder. (858 gets 860 and -107 gets -110).

Some pseudocode in your answer would be appreciated.

2

There are 2 best solutions below

0
On

Choose a gridstep $s$ between $0$ and $\min (|min|, max)$ (this will be the distance between any two consecutive vertical gridlines).

Let $m = \lfloor \dfrac {|min|} s \rfloor$ and $M = \lfloor \dfrac {max} s \rfloor$, where $\lfloor \cdot \rfloor$ is the floor function (also known as the integer part). Then draw a vertical gridline at each point of the form $k s$ with $-m \le k \le M$; the line with $k=0$ will pass through the origin. Note that, in principle, there exist values of $min$ and $max$ such that no such vertical gridline passes through these endpoints (for each $s$ they are of this unpleasant form if $\dfrac {min} s, \dfrac {max} s \notin \Bbb Z$).

Your graph will have $N = \dfrac {max - min} s$ vertical gridlines. If you want to start with a fixed number of gridlines, then choose $s$ as $\dfrac {max - min} N$.

3
On

Round the low value to the nearest lower multiple of $10$ and the high value to the nearest higher multiple of $10$.

With your example,

$$[-107,858]\to\left[10\lfloor\frac{-107}{10}\rfloor,10\lceil\frac{858}{10}\rceil\right]=[-110,860].$$

In programming, when the bounds are integer, this can be achieved by means of the $\%$ operator, with

$$[(\min-9) \% 10, (\max+9) \% 10].$$

Beware that you need to subtract $9$ on the left to achieve a floor of a negative value, and add $9$ on the right to obtain a ceiling.