## Maths

Maths — Mathematical utility functions

## Functions

#define | GWY_ROUND()
#define | gwy_round()
#define | gwy_clamp()
gdouble | (*GwyRealFunc) ()
gdouble | gwy_math_humanize_numbers ()
gboolean | gwy_math_is_in_polygon ()
gint | gwy_math_find_nearest_line ()
gint | gwy_math_find_nearest_point ()
gint | gwy_math_find_nearest_corner ()
gint | gwy_math_cut_line_by_rectangle ()
gdouble * | gwy_math_lin_solve ()
gdouble * | gwy_math_lin_solve_rewrite ()
gboolean | gwy_math_tridiag_solve_rewrite ()
gdouble * | gwy_math_fit_poly ()
gdouble * | gwy_math_fit_poly_equidist ()
gboolean | gwy_math_choleski_decompose ()
void | gwy_math_choleski_solve ()
gboolean | gwy_math_choleski_invert ()
guint | gwy_math_curvature_at_apex ()
guint | gwy_math_curvature_at_origin ()
gint | gwy_math_plane_coefficients ()
gboolean | gwy_math_refine_maximum_1d ()
gboolean | gwy_math_refine_maximum_2d ()
gdouble | gwy_math_find_minimum_1d ()
guint * | gwy_check_regular_2d_grid ()
guint * | gwy_check_regular_2d_lattice ()
void | gwy_accumulate_counts ()
gdouble * | gwy_math_fill ()
gdouble * | gwy_math_linspace ()
gdouble | gwy_math_median ()
gdouble | gwy_math_kth_rank ()
void | gwy_math_kth_ranks ()
void | gwy_math_percentiles ()
void | gwy_math_sort ()
void | gwy_guint_sort ()
void | gwy_math_sort_with_index ()
gdouble | gwy_math_mean ()
gdouble | gwy_math_trimmed_mean ()
gint | gwy_compare_double ()
gdouble | gwy_xlnx_int ()
gdouble | gwy_canonicalize_angle ()
guint | gwy_math_histogram ()
int | gwy_isnan ()
int | gwy_isinf ()
int | gwy_isnormal ()
double | gwy_exp10 ()
void | gwy_sincos ()
double | gwy_powi ()
gdouble | gwy_sinc ()
gdouble | gwy_deg2rad ()
gdouble | gwy_rad2deg ()

## Types and Values

#define | GWY_SQRT3
#define | GWY_SQRT_PI
enum | GwyPercentileInterpolationType

## Includes

    #include <libgwyddion/gwyddion.h>

## Description

Function `gwy_math_humanize_numbers()` deals with number representation.

Nearest object finding functions `gwy_math_find_nearest_line()` and `gwy_math_find_nearest_point()` can be useful in widget and vector layer implementation.

And `gwy_math_lin_solve()`, `gwy_math_lin_solve_rewrite()`, and `gwy_math_fit_poly()` are general purpose numeric methods.

## Functions

### GWY_ROUND()

    #define GWY_ROUND(x) ((gint)floor((x) + 0.5))

Rounds a floating point number to nearest integer.

#### Parameters

x | A double value. |

### gwy_round()

    #define gwy_round(x) ((gint)floor((x) + 0.5))

Rounds a floating point number to nearest integer.

#### Parameters

x | A double value. |

### gwy_clamp()

    #define gwy_clamp(x, lower, upper) fmin(fmax((x), (lower)), (upper))

Clamps a floating point number to an interval.

The behaviour is undefined if `lower` is larger than `upper` .

The macro uses `fmax()` and `fmin()` and evaluates its arguments only once.

#### Parameters

x | A double value. |
lower | Lower bound. |
upper | Upper bound. |

### GwyRealFunc()

    gdouble
    (*GwyRealFunc) (gdouble x,
                    gpointer user_data);

Type of single-variable real function with user data.

#### Parameters

x | Value to calculate the function for. |
user_data | User data passed to the driver function. | [closure]

### gwy_math_humanize_numbers()

    gdouble
    gwy_math_humanize_numbers (gdouble unit,
                               gdouble maximum,
                               gint *precision);

Finds a human-friendly representation for a range of numbers.

#### Parameters

unit | The smallest possible step. |
maximum | The maximum possible value. |
precision | A location to store `printf()` precession, if not `NULL`. | [out][optional]

#### Returns

The magnitude i.e., a power of 1000.

### gwy_math_is_in_polygon()

    gboolean
    gwy_math_is_in_polygon (gdouble x,
                            gdouble y,
                            const gdouble *poly,
                            guint n);

Establishes wether the test point `x` , `y` is inside the polygon `poly` . The polygon can be defined either clockwise or anti-clockwise and can be a concave, convex or self-intersecting polygon.

Result can be either TRUE or FALSE if the test point is *exactly* on an edge.

#### Parameters

x | The x coordinate of the test point. |
y | The y coordinate of the test point. |
poly | An array of coordinate pairs (points) that define a polygon. |
n | The number of corners of the polygon. |

#### Returns

`TRUE` if the test point is inside poly and `FALSE` otherwise.

### gwy_math_find_nearest_line()

    gint
    gwy_math_find_nearest_line (gdouble x,
                                gdouble y,
                                gdouble *d2min,
                                const gdouble *coords,
                                gint n,
                                const gdouble *metric);

Finds the line nearest to the given point.

#### Parameters

x | X-coordinate of the point. |
y | Y-coordinate of the point. |
d2min | Where to store the squared minimal distance, or `NULL`. | [out][optional]
coords | Line coordinates stored as x00, y00, x01, y01, x10, y10, etc. |
n | The number of lines (i.e. `coords` has 4×`n` items). |
metric | Metric matrix (2x2, but stored sequentially by rows: m11, m12, m21, m22), it must be positive definite. Vector norm is then calculated as m11*x*x + (m12 + m21)*x*y + m22*y*y. It can be `NULL`, standard Euclidean metric is then used. | [array fixed-size=4][nullable]

#### Returns

The line number. It may return -1 if (`x` , `y` ) doesn't lie in the orthogonal stripe of any of the lines.

### gwy_math_find_nearest_point()

    gint
    gwy_math_find_nearest_point (gdouble x,
                                 gdouble y,
                                 gdouble *d2min,
                                 const gdouble *coords,
                                 gint n,
                                 const gdouble *metric);

Finds the point nearest to the given point.

#### Parameters

x | X-coordinate of the point. |
y | Y-coordinate of the point. |
d2min | Location to store the squared minimal distance to, or `NULL`. | [out][optional]
coords | Point coordinates stored as x0, y0, x1, y1, x2, y2, etc. |
n | The number of points (i.e. `coords` has 2×`n` items). |
metric | Metric matrix (2x2, but stored sequentially by rows: m11, m12, m21, m22). Vector norm is then calculated as m11*x*x + (m12 + m21)*x*y + m22*y*y. It can be `NULL`, standard Euclidean metric is then used. | [array fixed-size=4][nullable]

#### Returns

The point number.

### gwy_math_find_nearest_corner()

    gint
    gwy_math_find_nearest_corner (gdouble x,
                                  gdouble y,
                                  gdouble *d2min,
                                  const gdouble *coords,
                                  gint n,
                                  const gdouble *metric);

Finds the rectangle corner nearest to the given point.

The rectangles are given as non-redundant coordinates, i.e. only four numbers per rectangle. If you already have all the 4×2 coordinates per rectangle use `gwy_math_find_nearest_point()` instead.

The quadruples of points are interpreted as pairs of opposite rectangle corners. They are the 0th and 2nd corners of the rectangle. The 1st point has coordinates (`x0` , `y1` ) and the 3rd has coordinates (`x1` , `y0` ). Meaning we move away from a given corner by keeping `x` and changing `y` , and towards a given corner by keeping `y` and changing `x` .

#### Parameters

x | X-coordinate of the point. |
y | Y-coordinate of the point. |
d2min | Location to store the squared minimal distance to, or `NULL`. | [out][optional]
coords | Corner coordinates stored as x00, y00, x01, y01, x10, y10, etc. |
n | The number of rectangles (i.e. `coords` has 4×`n` items). |
metric | Metric matrix (2x2, but stored sequentially by rows: m11, m12, m21, m22). Vector norm is then calculated as m11*x*x + (m12 + m21)*x*y + m22*y*y. It can be `NULL`, standard Euclidean metric is then used. | [array fixed-size=4][nullable]

#### Returns

The corner number.

### gwy_math_cut_line_by_rectangle()

    gint
    gwy_math_cut_line_by_rectangle (gdouble x,
                                    gdouble y,
                                    gdouble vx,
                                    gdouble vy,
                                    const gdouble *rect,
                                    gdouble *t);

Finds the closest intersection of a half-line with a rectangle side.

The intersection time is such that (`x` + `t` ×`vx` , `y` + `t` ×`vy` ) lies on a side of the rectangle. If the point is inside the rectangle, there is always exactly one intersection provided (`vx` , `vy` ) is non-zero. If the point is outside, there may be multiple intersections. The closest one corresponds to the line entering the rectangle and the corresponding `t` is computed. There may not be any intersections, for instance when the half-line is pointed away from the rectangle.

The side numbering corresponds to `rect` . Each rectangle side has exactly one coordinate constant and equal to x₁, y₁, x₂ or y₂. So the corresponding index in `rect` is returned.

#### Parameters

x | X-coordinate of the point. |
y | Y-coordinate of the point. |
vx | X-component of the line vector. |
vy | Y-component of the line vector. |
rect | Quadruple of points (x₁, y₁, x₂, y₂) defining two opposite corners of the rectangle. | [array fixed-size=4]
t | Location where to store the intersection time. If the function return a negative value the intersection time is not set. | [out]

#### Returns

Non-negative number if an intersection was found, encoding the side. Negative number if the half-line does not intersect the rectangle.

### gwy_math_lin_solve()

    gdouble *
    gwy_math_lin_solve (gint n,
                        const gdouble *matrix,
                        const gdouble *rhs,
                        gdouble *result);

Solve a regular system of linear equations.

#### Parameters

n | The size of the system. |
matrix | The matrix of the system (`n` times `n` ), ordered by row, then column. |
rhs | The right hand side of the sytem. |
result | Where the result should be stored. May be `NULL` to allocate a fresh array for the result. | [nullable]

#### Returns

The solution (`result` if it wasn't `NULL`), may be `NULL` if the matrix is singular.

### gwy_math_lin_solve_rewrite()

    gdouble *
    gwy_math_lin_solve_rewrite (gint n,
                                gdouble *matrix,
                                gdouble *rhs,
                                gdouble *result);

Solves a regular system of linear equations.

This is a memory-conservative version of `gwy_math_lin_solve()` overwriting `matrix` and `rhs` with intermediate results.

#### Parameters

n | The size of the system. |
matrix | The matrix of the system (`n` times `n` ), ordered by row, then column. |
rhs | The right hand side of the sytem. |
result | Where the result should be stored. May be `NULL` to allocate a fresh array for the result. | [nullable]

#### Returns

The solution (`result` if it wasn't `NULL`), may be `NULL` if the matrix is singular.

### gwy_math_tridiag_solve_rewrite()

    gboolean
    gwy_math_tridiag_solve_rewrite (gint n,
                                    gdouble *d,
                                    const gdouble *a,
                                    const gdouble *b,
                                    gdouble *rhs);

Solves a tridiagonal system of linear equations.

#### Parameters

n | The dimension of `d` . |
d | The diagonal of a tridiagonal matrix, its contents will be overwritten. |
a | The above-diagonal stripe (it has `n` -1 elements). |
b | The below-diagonal stripe (it has `n` -1 elements). |
rhs | The right hand side of the system, upon return it will contain the solution. |

#### Returns

`TRUE` if the elimination suceeded, `FALSE` if the system is (numerically) singular. The contents of `d` and `rhs` may be overwritten in the case of failure too, but not to any meaningful values.

### gwy_math_fit_poly()

    gdouble *
    gwy_math_fit_poly (const gdouble *xdata,
                       const gdouble *ydata,
                       gint ndata,
                       gint degree,
                       gdouble *coeffs);

Fits a polynomial through a general (x, y) data set.

#### Parameters

xdata | Independent variable data (of size `ndata` ). |
ydata | Dependent variable data (of size `ndata` ). |
ndata | The number of items in `xdata` , `ydata` . |
degree | The degree of polynomial to fit. |
coeffs | An array of size `degree` +1 to store the coefficients to, or `NULL` (a fresh array is allocated then). | [nullable]

#### Returns

The coefficients of the polynomial (`coeffs` when it was not `NULL`, otherwise a newly allocated array).

### gwy_math_fit_poly_equidist()

    gdouble *
    gwy_math_fit_poly_equidist (const gdouble *ydata,
                                gint ndata,
                                gdouble x0,
                                gdouble dx,
                                gint degree,
                                gdouble *coeffs);

Fits a polynomial through a data set with equidistant abscissa points.

#### Parameters

ydata | Dependent variable data (of size `ndata` ). |
ndata | The number of items in `ydata` . |
x0 | Independent variable value corresponding to `ydata` [0]. |
dx | Step of independent variable. |
degree | The degree of polynomial to fit. |
coeffs | An array of size `degree` +1 to store the coefficients to, or `NULL` (a fresh array is allocated then). | [nullable]

#### Returns

The coefficients of the polynomial (`coeffs` when it was not `NULL`, otherwise a newly allocated array).

### gwy_math_choleski_decompose()

    gboolean
    gwy_math_choleski_decompose (gint n,
                                 gdouble *matrix);

Decomposes a symmetric positive definite matrix in place.

#### Parameters

n | The dimension of `a` . |
matrix | Lower triangular part of a symmetric matrix, stored by rows, i.e., matrix = [a_00 a_10 a_11 a_20 a_21 a_22 a_30 ...]. |

#### Returns

Whether the matrix was really positive definite. If `FALSE`, the decomposition failed and `a` does not contain any meaningful values.

### gwy_math_choleski_solve()

    void
    gwy_math_choleski_solve (gint n,
                             const gdouble *decomp,
                             gdouble *rhs);

Solves a system of linear equations with predecomposed symmetric positive definite matrix `a` and right hand side `b` .

#### Parameters

n | The dimension of `a` . |
decomp | Lower triangular part of Choleski decomposition as computed by `gwy_math_choleski_decompose()`. |
rhs | Right hand side vector. Is is modified in place, on return it contains the solution. |

### gwy_math_choleski_invert()

    gboolean
    gwy_math_choleski_invert (gint n,
                              gdouble *matrix);

Inverts a symmetric positive definite matrix in place.

#### Parameters

n | Matrix size. |
matrix | Lower triangular part of a symmetric matrix, stored by rows, i.e., matrix = [a_00 a_10 a_11 a_20 a_21 a_22 a_30 ...]. |

#### Returns

Whether the matrix was really positive definite. If `FALSE`, the inversion failed and `matrix` does not contain any meaningful values.

### gwy_math_curvature_at_apex()

    guint
    gwy_math_curvature_at_apex (const gdouble *coeffs,
                                gdouble *kappa1,
                                gdouble *kappa2,
                                gdouble *phi1,
                                gdouble *phi2,
                                gdouble *xc,
                                gdouble *yc,
                                gdouble *zc);

Calculates curvature parameters at the apex from two-dimensional quadratic polynomial coefficients.

See also `gwy_math_curvature_at_origin()` which computes the local surface curvature at `x` =0 and `y` =0.

If the quadratic surface was obtained by fitting the dimensions of the fitted area should not differ, in the lateral coordinates used, by many orders from 1. Otherwise the recognition of flat surfaces might not work.

Curvatures have signs, positive mean a concave (cup-like) surface, negative mean a convex (cap-like) surface. They are ordered including the sign.

Directions are angles from the interval [-π/2, π/2].

If the quadratic surface is degenerate, i.e. flat in at least one direction, the centre is undefined. The centre is then chosen as the closest point the origin of coordinates. For flat surfaces this means the origin is simply returned as the centre position. Consequently, you should use Cartesian coordinates with origin in a natural centre, for instance centre of image or grain.

#### Parameters

coeffs | Array of the six polynomial coefficients of a quadratic surface in the following order: 1, x, y, x², xy, y². | [array fixed-size=6]
kappa1 | Location to store the smaller curvature to. | [out]
kappa2 | Location to store the larger curvature to. | [out]
phi1 | Location to store the direction of the smaller curvature to. | [out]
phi2 | Location to store the direction of the larger curvature to. | [out]
xc | Location to store x-coordinate of the centre of the quadratic surface. | [out]
yc | Location to store y-coordinate of the centre of the quadratic surface. | [out]
zc | Location to store value at the centre of the quadratic surface. | [out]

#### Returns

The number of curved dimensions (0 to 2).

### gwy_math_curvature_at_origin()

    guint
    gwy_math_curvature_at_origin (const gdouble *coeffs,
                                  gdouble *kappa1,
                                  gdouble *kappa2,
                                  gdouble *phi1,
                                  gdouble *phi2);

Calculates curvature parameters at origin from two-dimensional quadratic polynomial coefficients.

See `gwy_math_curvature_at_apex()` for discussion of scaling and sign convenrions. This function function differs from it by computing the local surface curvature at `x` =0 and `y` =0, whereas `gwy_math_curvature_at_apex()` computes the curvature at the apex of the parabolic surface.

The array `coeffs` is consistent with `gwy_math_curvature_at_apex()`, even though here the constant term is not used.

#### Parameters

coeffs | Array of the six polynomial coefficients of a quadratic surface in the following order: 1, x, y, x², xy, y². | [array fixed-size=6]
kappa1 | Location to store the smaller curvature to. | [out]
kappa2 | Location to store the larger curvature to. | [out]
phi1 | Location to store the direction of the smaller curvature to. | [out]
phi2 | Location to store the direction of the larger curvature to. | [out]

#### Returns

The number of curved dimensions (0 to 2).

### gwy_math_plane_coefficients()

    gint
    gwy_math_plane_coefficients (gdouble sumx2,
                                 gdouble sumxy,
                                 gdouble sumy2,
                                 gdouble sumxz,
                                 gdouble sumyz,
                                 gsize n,
                                 gdouble *bx,
                                 gdouble *by);

Calculates minimum-norm plane coefficients.

The `x` and `y` coordinates are assumed to form a grid with step 1 (or larger) in each direction, at least approximately. The sums entering the calculation must be calculated with respet to the centre of mass of the point set in the `xy` plane.

The function then calculates the plane coefficients (in the same integer coordinates), in the sense of minimum-norm solution in the degenerated cases. A typical degenerate case is that all points are collinear. In such case the coefficient along the line can be determined, but the coefficient in the orthogonal direction cannot – and is set to zero (and then they are projected into `x` and `y` ). An even more degenerate case is a single point for which the minimum-norm coefficients are zero.

#### Parameters

sumx2 | Sum of squared integer `x` -coordinates. |
sumxy | Sum of products of integer `x` - and `y` -coordinates. |
sumy2 | Sum of squared integer `y` -coordinates. |
sumxz | Sum of products of integer `x` -coordinates and `z` values. |
sumyz | Sum of products of integer `y` -coordinates and `z` values. |
n | Number of points. |
bx | Location where to store the plane `x` -coeffictient. | [out]
by | Location where to store the plane `y` -coeffictient. | [out]

#### Returns

The rank, which is 2 in non-degenerate cases, 1 for collinear points, 0 for a single point and -1 for no points at all (which is the same here, but still useful to distinguish).

### gwy_math_refine_maximum_1d()

    gboolean
    gwy_math_refine_maximum_1d (const gdouble *y,
                                gdouble *x);

Performs subpixel refinement of parabolic a one-dimensional maximum.

The central value corresponds to x-coordinate 0, distances between values are unity. The refinement is based by fitting a parabola through the maximum. If it fails or the calculated maximum lies farther than the surrounding values the function sets the refined maximum to the origin and returns `FALSE`.

#### Parameters

y | Array of length 3, containing the neighbourhood values with the maximum in the centre. | [array fixed-size=3]
x | Location to store the refined `x` -coordinate. | [out]

#### Returns

`TRUE` if the refinement succeeded, `FALSE` if it failed. The value of `x` is usable regardless of the return value.

### gwy_math_refine_maximum_2d()

    gboolean
    gwy_math_refine_maximum_2d (const gdouble *z,
                                gdouble *x,
                                gdouble *y);

Performs subpixel refinement of parabolic a two-dimensional maximum.

The central value corresponds to coordinates (0,0), distances between values are unity. The refinement is based by fitting a two-dimensional parabola through the maximum. If it fails or the calculated maximum lies farther than the surrounding values the function sets the refined maximum to the origin and returns `FALSE`.

#### Parameters

z | Array of length 9, containing the square 3x3 neighbourhood values in matrix order and with the maximum in the centre. | [array fixed-size=9]
x | Location to store the refined `x` -coordinate. | [out]
y | Location to store the refined `y` -coordinate. | [out]

#### Returns

`TRUE` if the refinement succeeded, `FALSE` if it failed. The values of `x` and `y` are usable regardless of the return value.

### gwy_math_find_minimum_1d()

    gdouble
    gwy_math_find_minimum_1d (GwyRealFunc function,
                              gdouble a,
                              gdouble b,
                              gpointer user_data);

Finds a minimum of a real function in a finite interval.

The function simply does what it says on the tin. If there are multiple minima in [a,b] any of them can be returned, even though some effort to scan the interval is made. There is no requiement for the minimum to lie inside [a,b]; if it occurrs at one of the endpoints, the endpoint is returned.

#### Parameters

function | Function to minimize. | [scope call]
a | First interval endpoint. |
b | Second interval endpoint. |
user_data | User data passed to `function` . |

### gwy_check_regular_2d_grid()

    guint *
    gwy_check_regular_2d_grid (const gdouble *coords,
                               guint stride,
                               guint n,
                               gdouble tolerance,
                               guint *xres,
                               guint *yres,
                               GwyXY *xymin,
                               GwyXY *xystep);

Detects if points in plane form a regular rectangular grid oriented along the Cartesian axes.

Points lying in one straight line are not considered to form a rectangle.

When the function fails, i.e. the points do not form a regular grid, the values of output arguments are undefined.

See also `gwy_check_regular_2d_lattice()` which is more lenient.

#### Parameters

coords | Array of `n` coordinate pairs in plane. You can also typecast GwyXY or GwyXYZ to doubles. |
stride | Actual number of double values in one block. It must be at least 2 if `coords` contains just alternating `x` and `y` . If you pass an typecast GwyXYZ array give stride as 3, etc. |
n | Number of items in `coords` . |
tolerance | Relative distance from pixel center which is still considered OK. Pass a negative value for some reasonable default. The maximum meaningful value is 0.5, beyond that the point would end up in a different pixel. |
xres | Location where to store the number of columns. | [out]
yres | Location where to store the number of rows. | [out]
xymin | Location where to store the minimum coordinates (top left corner of the corresponding image). | [out]
xystep | Location where to store the pixel size. | [out]

#### Returns

On success, a newly allocated array mapping grid indices (`i` *`xres` +`j` ) to indices in `coords` . `NULL` is returned on failure.

### gwy_check_regular_2d_lattice()

    guint *
    gwy_check_regular_2d_lattice (const gdouble *coords,
                                  guint stride,
                                  guint n,
                                  guint *xres,
                                  guint *yres,
                                  GwyXY *xymin,
                                  GwyXY *vx,
                                  GwyXY *vy,
                                  gdouble *maxdiff);

Detects if points in plane form more or less a regular lattice.

At present points lying in one straight line are not considered to form a lattice and neither are points sets with duplicate points (corresponding to the same lattice point).

Any rotation in the plane, a moderate amount of missing points, moderate skew and moderate deviations from the exact lattice positions should not prevent lattice detection. Large defects may, and so may large differences between lattice step sizes. The function prefers basis vectors `vx` and `vy` in which the point set resembles a rectangle. When the goal is to render the data to an image this is normally the desired behaviour. However, for an odd overal shape of the point set the result may not be useful.

The caller can check for holes in the lattice by comparing returned `xres` ×`yres` with `n` , for skew by evaluating the angle between `vx` and `vy` and for deviations by inspecting `maxdiff` .

When the function fails, i.e. return `NULL`, the values of output arguments are undefined.

See also `gwy_check_regular_2d_grid()` which is faster for simple complete Cartesian grids and may work better for them if the steps in `x` and `y` differ a lot.

#### Parameters

coords | Array of `n` coordinate pairs in plane. You can also typecast GwyXY or GwyXYZ to doubles. |
stride | Actual number of double values in one block. It must be at least 2 if `coords` contains just alternating `x` and `y` . If you pass an typecast GwyXYZ array give stride as 3, etc. |
n | Number of items in `coords` . |
xres | Location where to store the number of columns. | [out]
yres | Location where to store the number of rows. | [out]
xymin | Location where to store the minimum coordinates (top left corner of the corresponding image). | [out]
vx | Location where to store the pixel step vector along `x` in the image. | [out]
vy | Location where to store the pixel step vector along `y` in the image. | [out]
maxdiff | Location where to store the maximum difference of a point from exact lattice location, or `NULL`. The value is in image pixel coordinates, i.e. value 1 corresponds to lattice step. | [out][optional]

#### Returns

On success, a newly allocated array mapping grid indices (`i` *`xres` +`j` ) to indices in `coords` . `NULL` is returned on failure.

### gwy_accumulate_counts()

    void
    gwy_accumulate_counts (guint *array,
                           gint n,
                           gboolean do_rewind);

Transforms counts in histogram bins to cumulative counts.

Each element of the array becomes the sum of previous elements, possibly plus itself. The behaviour depends on `do_rewind` .

If `do_rewind` is `FALSE` each elements becomes the sum of all previous elements plus itself. The function only works with `n` elements of `array` . The array [3, 1, 5, 2] with `n` =4 is transformed to [3, 4, 9, 11].

Often, this function is used for transforming block sizes to indices where a block starts. In such case pass `TRUE` and `array` must have `n` +1 elements because the items are effectively shifted right by one. The first element becomes zero and the (`n` +1)-th one becomes the sum of all elements up to `n` -1. The array [3, 1, 5, 2, ?] with `n` =4 becomes [0, 3, 4, 9, 11]. The value marked ? is not read, but is overwritten.

#### Parameters

array | Array of `n` or `n` +1 items, usually representing histogram bins. |
n | The number of histogram bins. Not the array size. |
do_rewind | `TRUE` to ‘rewind’ the counts, making them start from 0. If you pass `TRUE` `array` must have `n` +1 elements. |

### gwy_math_fill()

    gdouble *
    gwy_math_fill (gdouble *array,
                   gsize n,
                   gdouble value);

Fills an array with a constant.

#### Parameters

array | Array with `n` elements to fill with values, or `NULL`. | [array length=n][nullable][transfer full]
n | Number of items in `array` . |
value | Value to fill the array with. |

#### Returns

`array` itself if it was not `NULL`. If `array` is `NULL` a new array is allocated and returned.

[array length=n][transfer full]

### gwy_math_linspace()

    gdouble *
    gwy_math_linspace (gdouble *array,
                       gsize n,
                       gdouble first,
                       gdouble step);

Fills an array with a arithmetic progression of numbers.

Element `i` is set to `first` + `i` *`step` .

Note that the arguments differ from the similar numpy function.

#### Parameters

array | Array with `n` elements to fill with values, or `NULL`. | [array length=n][nullable][transfer full]
n | Number of items in `array` . |
first | Value the first item should be set to. |
step | Difference between consecutive values. |

#### Returns

`array` itself if it was not `NULL`. If `array` is `NULL` a new array is allocated and returned.

[array length=n][transfer full]

### gwy_math_median()

    gdouble
    gwy_math_median (gdouble *array,
                     gsize n);

Finds median of an array of values using Quick select algorithm.

See `gwy_math_kth_rank()` for details of how the values are shuffled.

#### Parameters

array | Array of doubles. It is shuffled by this function. | [array length=n]
n | Number of items in `array` . |

#### Returns

The median value of `array` .

### gwy_math_kth_rank()

    gdouble
    gwy_math_kth_rank (gdouble *array,
                       gsize n,
                       gsize k);

Finds k-th item of an array of values using Quick select algorithm.

The value positions change as follows. The returned value is guaranteed to be at `k` -th position in the array (i.e. correctly ranked). All other values are correctly ordered with respect to this value: preceeding values are smaller (or equal) and following values are larger (or equal).

#### Parameters

array | Array of doubles. It is shuffled by this function. | [array length=n]
n | Number of items in `array` . |
k | Rank of the value to find (from lowest to highest). |

#### Returns

The `k` -th value of `array` if it was sorted.

### gwy_math_kth_ranks()

    void
    gwy_math_kth_ranks (gdouble *array,
                        gsize n,
                        const guint *k,
                        guint nk,
                        gdouble *values);

Finds simultaneously several k-th items of an array of values.

The values are shuffled similarly to `gwy_math_kth_rank()`, except that the guarantee holds for all given ranks simultaneously. All values with explicitly requested ranks are at their correct positions and all values lying between them in the array are also between them numerically.

#### Parameters

array | Array of doubles. It is shuffled by this function. | [array length=n]
n | Number of items in `array` . |
k | Ranks of the value to find. |
nk | Number of ranked values to find (sizes of arrays `k` and `values` ). |
values | Array where to store values with ranks (from smallest to highest) given in `k` . |

### gwy_math_percentiles()

    void
    gwy_math_percentiles (gdouble *array,
                          gsize n,
                          GwyPercentileInterpolationType interp,
                          const gdouble *p,
                          guint np,
                          gdouble *values);

Finds simultaneously several percentiles of an array of values.

The values in `array` are shuffled similarly to `gwy_math_kth_ranks()`. However, it is difficult to state how exactly `p` translates to the values that become correctly ranked (and it depends on `interp` ). Hence you can only assume the set of values is preserved.

#### Parameters

array | Array of doubles. It is shuffled by this function. | [array length=n]
n | Number of items in `array` . |
interp | Interpolation method to use for percentiles that do not correspond exactly to an integer rank. |
p | Array of size `np` with the percentiles to compute. The values are in percents, i.e. from the range [0,100]. |
np | Number of percentiles to find. |
values | Array where to store values with percentiles given in `p` . |

### gwy_math_sort()

    void
    gwy_math_sort (gdouble *array,
                   gsize n);

Sorts an array of doubles using a quicksort algorithm.

This is usually about twice as fast as the generic quicksort function thanks to specialization for doubles.

#### Parameters

n | Number of items in `array` . |
array | Array of doubles to sort in place. | [array length=n]

### gwy_guint_sort()

    void
    gwy_guint_sort (guint *array,
                    gsize n);

Sorts an array of unsigned integers using a quicksort algorithm.

This is usually about twice as fast as the generic quicksort function thanks to specialization for integers.

#### Parameters

n | Number of items in `array` . |
array | Array of guint values to sort in place. | [array length=n]

### gwy_math_sort_with_index()

    void
    gwy_math_sort_with_index (gdouble *array,
                              gsize n,
                              guint *index_array);

Sorts an array of doubles using a quicksort algorithm, remembering the permutation.

The simplest and probably most common use of `index_array` is to fill it with numbers 0 to `n` -1 before calling `gwy_math_sort()`. After sorting, `index_array` [`i` ] then contains the original position of the `i` -th item of the sorted array.

#### Parameters

array | Array of doubles to sort in place. |
n | Number of items in `array` . |
index_array | Array of integer identifiers of the items that are permuted simultaneously with `array` . |

### gwy_math_mean()

    gdouble
    gwy_math_mean (const gdouble *array,
                   gsize n);

Calculates the mean of an array of values.

#### Parameters

array | Array of doubles. | [array length=n]
n | Number of items in `array` . |

#### Returns

The mean value.

### gwy_math_trimmed_mean()

    gdouble
    gwy_math_trimmed_mean (gdouble *array,
                           gsize n,
                           guint nlowest,
                           guint nhighest);

Finds trimmed mean of an array of values.

At least one value must remain after the trimming, i.e. `nlowest` + `nhighest` must be smaller than `n` . Usually one passes the same number as both `nlowest` and `nhighest` , but it is not a requirement.

The function can be also used to calculate normal mean values as it implements efficiently the cases when no trimming is done at either end. However, the array is still considered mutable. Use `gwy_math_mean()` which has a const array argument.

#### Parameters

array | Array of doubles. It is shuffled by this function. | [array length=n]
n | Number of items in `array` . |
nlowest | The number of lowest values to discard. |
nhighest | The number of highest values to discard. |

#### Returns

The trimmed mean.

### gwy_compare_double()

    gint
    gwy_compare_double (gconstpointer a,
                        gconstpointer b);

Compares two double values, given as pointers.

This function is suitable as GCompareFunc and can be also used with plain `qsort()`. The typical usage is sorting of arrays containing structs where the first item is a floating point value/coordinate, followed by additional data. For sorting of plain arrays of doubles use `gwy_math_sort()`.

It should only be used to sort normal numbers. The behaviour for NaNs is undefined.

#### Parameters

a | Pointer to a double. |
b | Pointer to a double. |

### gwy_xlnx_int()

    gdouble
    gwy_xlnx_int (guint x);

Calculates natural logarithm multiplied by the argument for integers.

The value for zero `x` is taken as the limit, i.e. zero.

This function is useful for entropy calculations where values of `n` *log(`n` ) can be evaulated a lot for small `n` . Therefore, values for small arguments are tabulated. For large arguments the function is evaluated using the standard `log()` function which is of course slower.

#### Parameters

x | Value to calculate `x` *log(`x` ) of. |

#### Returns

Value of `x` *log(`x` ).

### gwy_canonicalize_angle()

    gdouble
    gwy_canonicalize_angle (gdouble phi,
                            gboolean positive,
                            gboolean oriented);

Canonicalizes an angle to requested interval.

For `positive` =`FALSE`, `oriented` =`FALSE` the output interval is [-π/2,π/2].

For `positive` =`FALSE`, `oriented` =`TRUE` the output interval is [-π,π].

For `positive` =`TRUE`, `oriented` =`FALSE` the output interval is [0,π).

For `positive` =`TRUE`, `oriented` =`TRUE` the output interval is [0,2π).

#### Parameters

phi | Angle to canonicalize, in radians. |
positive | `TRUE` if a positive angle is requested, `FALSE` for outputs symmetrical around zero. |
oriented | `TRUE` for direction of a vector, `FALSE` for the direction of a line (i.e. with no distinction between forward and backward direction). |

#### Returns

Canonicalized angle, equivalent (in given sense) to `phi` .

### gwy_math_histogram()

    guint
    gwy_math_histogram (const gdouble *values,
                        guint n,
                        gdouble min,
                        gdouble max,
                        guint nbins,
                        guint *counts);

Counts the numbers of values falling into equal-sized bins.

The value of `min` must not be larger than `max` . The values may lie outside [`min` ,`max` ]. They are not counted in the histogram, nor the returned total.

Rounding rules for values exactly at the edge of two bins are arbitrary and must not be relied upon.

#### Parameters

values | Values to make histogram from. |
n | Number of values in `values` . |
min | Minimum value to consider (left edge of histogram). |
max | Maximum value to consider (right edge of histogram). |
nbins | Number of histogram bins (number of `counts` items), a positive number. |
counts | Array where to store the counts. |

#### Returns

The number of values inside the entire histogram, i.e. at most `n` but possibly a reduced count.

### gwy_isnan()

    int
    gwy_isnan (double x);

Alternative `isnan()` implementation which works even with GCC fast maths.

Gwyddion is usually compiled to not rely on IEEE-compliant behaviour of infinities and NaNs (not-a-numbers) and avoids such numbers. They are not normally allowed in Gwyddion files. If they occur in third-party files, the standard treatment is to skip or mask them and replace the underlying data with neutral values (interpolation) as necessary.

One side-effect of using the faster, finite-only maths is that standard functions such as `isnan()` may not work. They operate with NaNs by definition, and their behaviour is no longer well-defined. This prevents the detection of NaNs needed to get rid of them. Hence, functions like `gwy_isnan()` exist to detect reliably abnormal values during data import.

#### Parameters

x | Floating point number. |

### gwy_isinf()

    int
    gwy_isinf (double x);

Alternative `isinf()` implementation which works even with GCC fast maths.

See `gwy_isnan()` for remarks.

#### Parameters

x | Floating point number. |

### gwy_isnormal()

    int
    gwy_isnormal (double x);

Alternative `isnormal()` implementation which works even with GCC fast maths. * See `gwy_isnan()` for remarks

#### Parameters

x | Floating point number. |

### gwy_exp10()

    double
    gwy_exp10 (double x);

Calculates the value of base-10 exponential function.

This is an inline function or macro defined to a working `exp10()` implementation.

#### Parameters

x | Floating point number. |

### gwy_sincos()

    void
    gwy_sincos (double x,
                double *sinval,
                double *cosval);

Calculates simultaneously the sine and cosine functions.

This is an inline function or macro defined to a working `sincos()` implementation. If the system provides a `sincos()` function, it is usually faster than separate `sin()` and `cos()` calls.

#### Parameters

x | Floating point number. |
sinval | Location for the sine of `x` . |
cosval | Location for the cosine of `x` . |

### gwy_powi()

    double
    gwy_powi (double x,
              int i);

Calculates an integer power of a floating point number.

This is an inline function or macro defined to a working integer power implementation. If the compiler provides a builtin like GCC's `__builtin_powi()`, it is the implementation used.

#### Parameters

x | Floating point number. |
i | Integer power. |

### gwy_sinc()

    gdouble
    gwy_sinc (gdouble x);

Calculates the sinc function.

The sinc function is equal to sin(`x` )/`x` for non-zero `x` , and defined to the limit 1 for zero `x` .

#### Parameters

x | Value to calculate sinc (cardinal sine) of. |

#### Returns

Value of sinc(`x` ).

### gwy_deg2rad()

    gdouble
    gwy_deg2rad (gdouble x);

Converts an angle from degrees to radians.

#### Parameters

x | Angle in degrees. |

#### Returns

Value of `x` in radians.

### gwy_rad2deg()

    gdouble
    gwy_rad2deg (gdouble x);

Converts an angle from radians to degrees.

#### Parameters

x | Angle in radians. |

#### Returns

Value of `x` in degrees.

## Types and Values

### GWY_SQRT3

    #define GWY_SQRT3 1.73205080756887729352744634150587236694280525381038

The square root of 3.

### GWY_SQRT_PI

    #define GWY_SQRT_PI 1.77245385090551602729816748334114518279754945612237

The square root of pi.

### enum GwyPercentileInterpolationType

Type of interpolation for percentile calculation.

The interpolations are used when the percentile does not correspond exactly to a rank.

#### Members

GWY_PERCENTILE_INTERPOLATION_LINEAR | Linear interpolation of the two nearest values. |
GWY_PERCENTILE_INTERPOLATION_LOWER | Round the rank down to an integer. |
GWY_PERCENTILE_INTERPOLATION_HIGHER | Round the rank up to an integer. |
GWY_PERCENTILE_INTERPOLATION_NEAREST | Round the rank to nearest integer. |
GWY_PERCENTILE_INTERPOLATION_MIDPOINT | Average of the two nearest values. |

## See Also

GwyNLFitter, non-linear least square fitter