Math — Mathematical utility functions
#define  GWY_SQRT3 
#define  GWY_SQRT_PI 
GwyXY  
GwyXYZ 
#include <libgwyddion/gwyddion.h>
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_polynom()
are general purpose numeric
methods.
#define ROUND(x) ((gint)floor((x) + 0.5))
ROUND
is deprecated and should not be used in newlywritten code.
Rounds a number to nearest integer. Use GWY_ROUND
instead.
x 
A double value. 
#define GWY_ROUND(x) ((gint)floor((x) + 0.5))
Rounds a number to nearest integer.
x 
A double value. 
Since: 2.5
GwyXY * gwy_xy_new (gdouble x
,gdouble y
);
Creates Cartesian coordinates in plane.
This is mostly useful for language bindings.
x 
Xcoordinate. 

y 
Ycoordinate. 
New XY structure. The result must be freed using gwy_xy_free()
, not g_free()
.
Since: 2.47
GwyXY *
gwy_xy_copy (const GwyXY *xy
);
Copies Cartesian coordinates in plane.
xy 
Cartesian coordinates in plane. 
A copy of xy
. The result must be freed using gwy_xy_free()
, not g_free()
.
Since: 2.45
void
gwy_xy_free (GwyXY *xy
);
Frees Cartesian coordinates in plane created with gwy_xy_copy()
.
xy 
Cartesian coordinates in plane. 
Since: 2.45
GwyXYZ * gwy_xyz_new (gdouble x
,gdouble y
,gdouble z
);
Creates Cartesian coordinates in space.
This is mostly useful for language bindings.
x 
Xcoordinate. 

y 
Ycoordinate. 

z 
Zcoordinate. 
New XYZ structure. The result must be freed using gwy_xyz_free()
, not g_free()
.
Since: 2.47
GwyXYZ *
gwy_xyz_copy (const GwyXYZ *xyz
);
Copies Cartesian coordinates in space.
xyz 
Cartesian coordinates in space. 
A copy of xyz
. The result must be freed using gwy_xyz_free()
, not g_free()
.
Since: 2.45
void
gwy_xyz_free (GwyXYZ *xyz
);
Frees Cartesian coordinates in space created with gwy_xyz_copy()
.
xyz 
Cartesian coordinates in space. 
Since: 2.45
gdouble (*GwyRealFunc) (gdouble x
,gpointer user_data
);
gdouble gwy_math_humanize_numbers (gdouble unit
,gdouble maximum
,gint *precision
);
Finds a humanfriendly representation for a range of numbers.
unit 
The smallest possible step. 

maximum 
The maximum possible value. 

precision 
A location to store 
The magnitude i.e., a power of 1000.
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 anticlockwise and can be a concave, convex or selfintersecting polygon.
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. 
TRUE
if the test point is inside poly and FALSE
otherwise.
Since: 2.7
gint gwy_math_find_nearest_line (gdouble x
,gdouble y
,gdouble *d2min
,gint n
,const gdouble *coords
,const gdouble *metric
);
Finds the line from coords
nearest to the point (x
, y
).
x 
Xcoordinate of the point to search. 

y 
Ycoordinate of the point to search. 

d2min 
Where to store the squared minimal distance, or 

n 
The number of lines (i.e. 

coords 
Line coordinates stored as x00, y00, x01, y01, x10, y10, etc. 

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 
The line number. It may return 1 if (x
, y
) doesn't lie in the orthogonal stripe of any of the lines.
gint gwy_math_find_nearest_point (gdouble x
,gdouble y
,gdouble *d2min
,gint n
,const gdouble *coords
,const gdouble *metric
);
Finds the point from coords
nearest to the point (x
, y
).
x 
Xcoordinate of the point to search. 

y 
Ycoordinate of the point to search. 

d2min 
Location to store the squared minimal distance to, or 

n 
The number of points (i.e. 

coords 
Point coordinates stored as x0, y0, x1, y1, x2, y2, etc. 

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 
The point number.
gdouble * gwy_math_lin_solve (gint n
,const gdouble *matrix
,const gdouble *rhs
,gdouble *result
);
Solve a regular system of linear equations.
n 
The size of the system. 

matrix 
The matrix of the system ( 

rhs 
The right hand side of the sytem. 

result 
Where the result should be stored. May be 
The solution (result
if it wasn't NULL
), may be NULL
if the matrix is singular.
gdouble * gwy_math_lin_solve_rewrite (gint n
,gdouble *matrix
,gdouble *rhs
,gdouble *result
);
Solves a regular system of linear equations.
This is a memoryconservative version of gwy_math_lin_solve()
overwriting matrix
and rhs
with intermediate
results.
n 
The size of the system. 

matrix 
The matrix of the system ( 

rhs 
The right hand side of the sytem. 

result 
Where the result should be stored. May be 
The solution (result
if it wasn't NULL
), may be NULL
if the matrix is singular.
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.
n 
The dimension of 

d 
The diagonal of a tridiagonal matrix, its contents will be overwritten. 

a 
The abovediagonal stripe (it has 

b 
The belowdiagonal stripe (it has 

rhs 
The right hand side of the system, upon return it will contain the solution. 
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.
gdouble * gwy_math_fit_polynom (gint ndata
,const gdouble *xdata
,const gdouble *ydata
,gint n
,gdouble *coeffs
);
Fits a polynomial through a general (x, y) data set.
ndata 
The number of items in 

xdata 
Independent variable data (of size 

ydata 
Dependent variable data (of size 

n 
The degree of polynomial to fit. 

coeffs 
An array of size 
The coefficients of the polynomial (coeffs
when it was not NULL
, otherwise a newly allocated array).
gboolean gwy_math_choleski_decompose (gint n
,gdouble *matrix
);
Decomposes a symmetric positive definite matrix in place.
n 
The dimension of 

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 ...]. 
Whether the matrix was really positive definite. If FALSE
, the decomposition failed and a
does not
contain any meaningful values.
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
.
n 
The dimension of 

decomp 
Lower triangular part of Choleski decomposition as computed by 

rhs 
Right hand side vector. Is is modified in place, on return it contains the solution. 
gboolean gwy_math_choleski_invert (gint n
,gdouble *matrix
);
Inverts a symmetric positive definite matrix in place.
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 ...]. 
Whether the matrix was really positive definite. If FALSE
, the inversion failed and matrix
does not
contain any meaningful values.
Since: 2.46
guint gwy_math_curvature (const gdouble *coeffs
,gdouble *kappa1
,gdouble *kappa2
,gdouble *phi1
,gdouble *phi2
,gdouble *xc
,gdouble *yc
,gdouble *zc
);
Calculates curvature parameters at the apex from twodimensional quadratic polynomial coefficients.
This is an old name for gwy_math_curvature_at_apex()
. See the description there.
coeffs 
Array of the six polynomial coefficients of a quadratic surface in the following order: 1, x, y, x², xy, y². 

kappa1 
Location to store the smaller curvature to. 

kappa2 
Location to store the larger curvature to. 

phi1 
Location to store the direction of the smaller curvature to. 

phi2 
Location to store the direction of the larger curvature to. 

xc 
Location to store xcoordinate of the centre of the quadratic surface. 

yc 
Location to store ycoordinate of the centre of the quadratic surface. 

zc 
Location to store value at the centre of the quadratic surface. 
The number of curved dimensions (0 to 2).
Since: 2.22
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 twodimensional 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 (cuplike) surface, negative mean a convex (caplike) 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.
coeffs 
Array of the six polynomial coefficients of a quadratic surface in the following order: 1, x, y, x², xy, y². 

kappa1 
Location to store the smaller curvature to. 

kappa2 
Location to store the larger curvature to. 

phi1 
Location to store the direction of the smaller curvature to. 

phi2 
Location to store the direction of the larger curvature to. 

xc 
Location to store xcoordinate of the centre of the quadratic surface. 

yc 
Location to store ycoordinate of the centre of the quadratic surface. 

zc 
Location to store value at the centre of the quadratic surface. 
The number of curved dimensions (0 to 2).
Since: 2.61
guint gwy_math_curvature_at_origin (const gdouble *coeffs
,gdouble *kappa1
,gdouble *kappa2
,gdouble *phi1
,gdouble *phi2
);
Calculates curvature parameters at origin from twodimensional quadratic polynomial coefficients.
See gwy_math_curvature()
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()
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.
coeffs 
Array of the six polynomial coefficients of a quadratic surface in the following order: 1, x, y, x², xy, y². 

kappa1 
Location to store the smaller curvature to. 

kappa2 
Location to store the larger curvature to. 

phi1 
Location to store the direction of the smaller curvature to. 

phi2 
Location to store the direction of the larger curvature to. 
The number of curved dimensions (0 to 2).
Since: 2.61
gboolean gwy_math_refine_maximum_1d (const gdouble *y
,gdouble *x
);
Performs subpixel refinement of parabolic a onedimensional maximum.
The central value corresponds to xcoordinate 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
.
y 
Array of length 3, containing the neighbourhood values with the maximum in the centre. 

x 
Location to store the refined 
TRUE
if the refinement succeeded, FALSE
if it failed. The value of x
is usable regardless of the
return value.
Since: 2.49
gboolean gwy_math_refine_maximum_2d (const gdouble *z
,gdouble *x
,gdouble *y
);
Performs subpixel refinement of parabolic a twodimensional maximum.
The central value corresponds to coordinates (0,0), distances between values are unity. The refinement is based by
fitting a twodimensional 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
.
z 
Array of length 9, containing the square 3x3 neighbourhood values in matrix order and with the maximum in the centre. 

x 
Location to store the refined 

y 
Location to store the refined 
TRUE
if the refinement succeeded, FALSE
if it failed. The values of x
and y
are usable regardless of
the return value.
Since: 2.49
gboolean gwy_math_refine_maximum (const gdouble *z
,gdouble *x
,gdouble *y
);
Performs subpixel refinement of parabolic a twodimensional maximum.
An alias for gwy_math_refine_maximum_2d()
.
z 
Array of length 9, containing the square 3x3 neighbourhood values in matrix order and with the maximum in the centre. 

x 
Location to store the refined 

y 
Location to store the refined 
TRUE
if the refinement succeeded, FALSE
if it failed. The values of x
and y
are usable regardless of
the return value.
Since: 2.42
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.
function 
Function to minimize. 

a 
First interval endpoint. 

b 
Second interval endpoint. 

user_data 
User data passed to 
Since: 2.51
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.
coords 
Array of 

stride 
Actual number of double values in one block. It must be at least 2 if 

n 
Number of items in 

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. 

yres 
Location where to store the number of rows. 

xymin 
Location where to store the minimum coordinates (top left corner). 

xystep 
Location where to store the pixel size. 
On success, a newly allocated array mapping grid indices (i
*xres
+j
) to indices in coords
. NULL
is
returned on failure.
Since: 2.48
gdouble gwy_math_median (gsize n
,gdouble *array
);
Finds median of an array of values using Quick select algorithm.
See gwy_math_kth_rank()
for details of how the values are shuffled.
n 
Number of items in 

array 
Array of doubles. It is shuffled by this function. 
The median value of array
.
gdouble gwy_math_kth_rank (gsize n
,gdouble *array
,gsize k
);
Finds kth 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).
n 
Number of items in 

array 
Array of doubles. It is shuffled by this function. 

k 
Rank of the value to find (from lowest to highest). 
The k
th value of array
if it was sorted.
Since: 2.50
void gwy_math_kth_ranks (gsize n
,gdouble *array
,guint nk
,const guint *k
,gdouble *values
);
Finds simultaneously several kth 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.
n 
Number of items in 

array 
Array of doubles. It is shuffled by this function. 

nk 
Number of ranked values to find (sizes of arrays 

k 
Ranks of the value to find. 

values 
Array where to store values with ranks (from smallest to highest) given in 
Since: 2.50
void gwy_math_percentiles (gsize n
,gdouble *array
,GwyPercentileInterpolationType interp
,guint np
,const gdouble *p
,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.
n 
Number of items in 

array 
Array of doubles. It is shuffled by this function. 

interp 
Interpolation method to use for percentiles that do not correspond exactly to an integer rank. 

np 
Number of percentiles to find. 

p 
Array of size 

values 
Array where to store values with percentiles given in 
Since: 2.50
void gwy_math_sort (gsize n
,gdouble *array
);
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.
n 
Number of items in 

array 
Array of doubles to sort in place. 
void gwy_guint_sort (gsize n
,guint *array
);
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.
n 
Number of items in 

array 
Array of guint values to sort in place. 
Since: 2.50
void gwy_math_sort_with_index (gsize n
,gdouble *array
,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.
n 
Number of items in 

array 
Array of doubles to sort in place. 

index_array 
Array of integer identifiers of the items that are permuted simultaneously with 
Since: 2.50
gdouble gwy_math_trimmed_mean (gsize n
,gdouble *array
,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.
n 
Number of items in 

array 
Array of doubles. It is shuffled by this function. 

nlowest 
The number of lowest values to discard. 

nhighest 
The number of highest values to discard. 
The trimmed mean.
Since: 2.50
gdouble gwy_math_median_uncertainty (gsize n
,gdouble *array
,gdouble *uarray
);
Find the uncertainty value corresponding to data median.
Note that this is not the uncertainty arising from the calculation of the median. It is just the uncertainty of the single value that happens to be the data median. As such, the function is not very useful.
n 
Number of items in 

array 
Array of doubles. It is modified by this function. All values are kept, but their positions in the array change. 

uarray 
Array of value unvertainries. It is modified by this function. All values are kept, but their positions in the array change. 
The uncertainty of the median value.
Since: 2.23
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.
a 
Pointer to a double. 

b 
Pointer to a double. 
Since: 2.62
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.
x 
Value to calculate 
Value of x
*log(x
).
Since: 2.44
gdouble
gwy_sinc (gdouble x
);
Calculates the sinc function.
The sinc function is equal to sin(x
)/x
for nonzero x
, and defined to the limit 1 for zero x
.
x 
Value to calculate sinc (cardinal sine) of. 
Value of sinc(x
).
Since: 2.51
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π).
phi 
Angle to canonicalize, in radians. 

positive 


oriented 

Canonicalized angle, equivalent (in given sense) to phi
.
Since: 2.50
guint gwy_math_histogram (const gdouble *values
,guint n
,gdouble min
,gdouble max
,guint nbins
,guint *counts
);
Counts the numbers of values falling into equalsized 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.
values 
Values to make histogram from. 

n 
Number of values in 

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 
Array where to store the counts. 
The number of values inside the entire histogram, i.e. at most n
but possibly a reduced count.
Since: 2.49
#define GWY_SQRT3 1.73205080756887729352744634150587236694280525381038
The square root of 3.
#define GWY_SQRT_PI 1.77245385090551602729816748334114518279754945612237
The square root of pi.
typedef struct { gdouble x; gdouble y; } GwyXY;
Representation of Cartesian coordinates in plane.
gdouble 
Xcoordinate. 

gdouble 
Ycoordinate. 
Since: 2.45
typedef struct { gdouble x; gdouble y; gdouble z; } GwyXYZ;
Representation of Cartesian coordinates in space.
gdouble 
Xcoordinate. 

gdouble 
Ycoordinate. 

gdouble 
Zcoordinate. 
Since: 2.45
GwyNLFitter, nonlinear least square fitter;
Math Fallback,fallback mathematical functions