# Math bits

## Area within a simple closed contour

Given a simple (i.e. not self-intersecting) closed contour with line/arc/elliptic arc entities, the enclosed area is found by Green's Theorem

$S=\oint x dy$

This type of line integrals has closed forms for lines, arcs, and ellipses.

### Line

$\int_0^1 [x_0+(x_1-x_0)t](y_1-y_0)dt=\frac{1}{2}(x_1+x_0)t](y_1-y_0)$

where (x0,y0) and (x1,y1) are the start and end point of the line, perspectively.

### Arc

Ignoring the constant of integration, the antiderivative can be found as $\int (c_x + r \cos t)r\cos t dt= c_x r \sin t + \frac{1}{4}r^2\sin 2t + \frac{1}{2}r^2 t$

where cx is the x-coordinate of arc center, and r, t are radius and arc angle, respectively.

## The nearest point on an ellipse to a given point

An ellipse in the coordinates orientated alone its major and minor axes is given as,

$\begin{cases} \begin{array}{c} x=a\cos t\\ y=b\sin t \end{array} & 0\le t<2\pi\end{cases}$

The squared distance from a point on ellipse to a given point(x,y),

$\begin{array}{rcl} s^{2}&=&(x-a\cos t)^{2}+(y-b\sin t)^{2}\\ &=&x^{2}+y^{2}+a^{2}\cos^{2}t+b^{2}\sin^{2}t-2xa\cos t-2yb\sin t \end{array}$

The stationary points at the zero points of its first order derivative of t,

$\frac{d(s^{2})}{dt}=-a^{2}\sin2t+b^{2}\sin2t+2xa\sin t-2yb\cos t=0$

This stationary condition is a quartic equation of cos t. With variable change u = cos t,

γ2u4 − 2αγu3 + (α2 + β2 − γ2)u2 + 2αγu − α2 = 0

where α = 2ax, β = 2by, and γ = 2(a2b2).

For all solutions from the quartic equation, the minimum distance point is identified by the convex condition,

$\frac{d^{2}(s^{2})}{dt^{2}}=\gamma(1-2u^{2})+\alpha u+\frac{\beta^{2}u}{\alpha-\gamma u}>0$

## Given a circle, construct a tangent circle passing two given points

Given a circle, the path of center of all tangent circles passing a given point is either an ellipse or a hyperbola. A quadratic form of either ellipse or hyperbola is constructed for each of the given points, and the center of the circle to be constructed in on the intersections of these two quadratic forms. After locating of the circle center, the radius is found by the distance from either of the given points to the center.

LibreCAD has a powerful general quadratic form framework to ease the construction of such quadratic forms and location of intersections between two quadratic forms.

## modular function in LibreCAD

the standard glibc fmod(x, a) is not convenient here, since we need a modular function work the same way for both positive and negative numbers, instead, we use,

$remainder(x - \frac{a}{2},a)+\frac{a}{2}$