TITLE: How to evenly space a number of points in a rectangle?
QUESTION [6 upvotes]: Say I have a rectangle, with variable width and height, for example lets use:
width = 20
height = 30

I would like to put n amount of evenly spaced points inside this rectangle:
no of points = 400

How could I calculate the x and y coordinates of each point? Note, that I would like the borders to also have points.
Very rough example, I needed 12 points (but I could have wanted more or less):

REPLY [4 votes]: Looking for a square grid of size $w \times h$ with $n$ points in total.
$n_x$ points in $x$-direction, spacing $\Delta x$: 
$$
x_i = i \, \Delta x \quad i \in \{ 0, \ldots, n_x-1 \}
$$ 
and 
$$
(n_x -1) \, \Delta x = w
$$
$n_y$ points in $y$-direction, spacing $\Delta y$:
$$
y_j = j \, \Delta y \quad j \in \{ 0, \ldots, n_y-1 \}
$$ 
and 
$$
(n_y -1) \, \Delta y = h
$$
Total number of points: 
$$
n = n_x \, n_y
$$
Assuming $\Delta x = \Delta y$ one gets
$$
\Delta x = \frac{w}{n_x - 1} = \frac{h}{n_y - 1} = \Delta y \iff \\
n_y = \frac{h}{w} n_x + 1 - \frac{h}{w} 
$$
and then
$$
n = n_x n_y = \frac{h}{w} n_x^2 + \left( 1 - \frac{h}{w} \right) n_x \iff \\
\frac{w}{h} n + \frac{(w-h)^2}{4h^2} = \left( n_x + \frac{w-h}{2h} \right)^2
$$
which after taking the square root gives the wanted equation for $n_x$ in terms of $n$, $w$ and $h$:
$$
n_x = \sqrt{\frac{w}{h} n + \frac{(w-h)^2}{4h^2}} - \frac{w-h}{2h} \quad (*)
$$
(the negative solution was dropped). 
$n_x$ then should be put into $n_y = n / n_x$ and those values can be used to calculate the spacing $\Delta x = \Delta y$.
The interesting bit is that not every integer $n$ in $(*)$ will lead to an integer $n_x$ and then to another integer $n_y$. 
Example 1
Given are $n = 12$, $w = 3$, $h = 2$. We put this in equation $(*)$ and get
$$
n_x 
= \sqrt{\frac{3}{2}\cdot 12 + \frac{(3-2)^2}{4\cdot 2^2}} - \frac{3-2}{2\cdot 2}
= \sqrt{18 + \frac{1}{16}} - \frac{1}{4} = \frac{17}{4} - \frac{1}{4} = 4
$$
so we have $n_x = 4$ points along the $x$-direction. Further $n_y = n / n_x = 12 / 4 = 3$ points in $y$-direction. The spacing is $\Delta x = w / (n_x - 1) = 3 / (4 - 1) = 1$, a unit spacing and $\Delta y$ is the same.
Example 2
Given are $n = 400$, $w = 20$, $h = 30$. From equation $(*)$ we get
$n_x = 16.4974487803453$ and then $n_y = 24.2461731705179$.
So this won't work. 

But why not try $n = 17 \cdot 25 = 425\,$ with the given $w$ and $h$ values? And this is indeed confirmed by equation $(*)$. Here $\Delta x = \Delta y = 1.25$.
I hope it a got a little bit clear that not all combinations of the problem parameters $n$, $w$ and $h$ have a solution.