Skip to content
Last updated

API / geotoolkit / util / MathUtil / MathUtil

Class: MathUtil

util.MathUtil.MathUtil

The class Math contains methods for performing basic numeric operations and basic algorithms.

Table of contents

Constructors
  • [new MathUtil()](/solutions/geotoolkit/GeoToolkit_JS/apis/classes/geotoolkit.util.mathutil.mathutil.md#new mathutil())
Accessors
Methods

Contents

Constructors

new MathUtil()

• new MathUtil()

Accessors

epsilon

• Static get epsilon(): number

constant for epsilon equal to 1E-10

Returns

number


logMin

• Static get logMin(): number

constant for minimum logarithmic value to be display equal to 1E-10

Returns

number


quickSort

• Static get quickSort(): (array: any[] | number[], lo: number, hi: number, comparator: Comparator, swap: Swap) => void

Quick sort (in-place).

Returns

fn

▸ (array, lo, hi, comparator, swap): void

Quick sort (in-place).

Parameters
Name Type Description
arrayany[] | number[]array of numbers or objects
lonumberstarting index
hinumberending index (including)
comparatorComparatoroptional a function that defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
swapSwapoptional swap function to swap two elements of collection, like: function(array, i, j) { }
Returns

void


sortPointsClockwise

• Static get sortPointsClockwise(): (xArray: number[], yArray: number[], isClockwise?: boolean) => void

Sort given array clockwise around their center point.

Returns

fn

▸ (xArray, yArray, isClockwise?): void

Sort given array clockwise around their center point.

Parameters
Name Type Description
xArraynumber[]x-coordinate of points
yArraynumber[]y-coordinate of points
Optional isClockwiseboolean
Returns

void

Methods

calcCubicBezier

▸ Static calcCubicBezier(first, p1, p2, last, flatness?): Point[]

Bezier curves are often used to model smooth curves. calcCubicBezier Performs cubic Bezier approximation. The control points P1 and P2 are only used to provide directional information.The arc or circle is divided into four equal sections and each section fit to a cubic Bézier curve. When points are spaced far apart approximation is performed based on the precision(flatness) and control points on the same side of vector.

Parameters

Name Type Description
firstPointfirst point
p1Pointcontrol point #1
p2Pointcontrol point #2
lastPointlast point
Optional flatnessnumberprecision

Returns

Point[]

array of interpolated points if "param" is undefined or is an Array instance


calculateNeatLimits

▸ Static calculateNeatLimits(min, max, logScale?, centerOnZeroOnNegativeMin?, splitOnZero?): Range

This function computes human readable limits so that the returned interval is easily apprehended by the user.<br> To do so, it will compute a minimum and maximum that can be easily divided by 2.<br> Which means the user will immediately guess the mid and quarter values.<br> <br> The purpose of this function is not to provide accurately rounded limits but limits that will be easily apprehended.<br> Using the given limits can virtually remove the necessity of displaying the intermediates labels on a axis.<br> <br> For example it will return [0, 4000] for the values [790, 3050].<br> The user will easily guess the mid value to be 2000.<br>

Parameters

Name Type Description
minnumberThe minimum value
maxnumberThe maximum value
Optional logScalebooleanIf this should use a logarithmic scale instead of linear
Optional centerOnZeroOnNegativeMinbooleanIf this should center the limits around 0 if minimum is a negative value
Optional splitOnZerobooleanIf this should split neat limits result around 0, applicable only when Math.sign(minimum) != Math.sign(maximum)

Returns

Range

The computed neat limits


calculateNiceLimits

▸ Static calculateNiceLimits(min, max, desiredNumberOfTicks, minPadding?, maxPadding?): Limits

Create a "nice" range based on "Algorithm for Optimal Scaling on a Chart Axis".

Parameters

Name Type Description
minnumberminimum value
maxnumbermaximum value
desiredNumberOfTicksnumberdesired number of ticks
Optional minPaddingbooleanadd step padding at first or not
Optional maxPaddingbooleanadd step padding at the end or not

Returns

Limits

calculated limits


calculateRoundedLimits

▸ Static calculateRoundedLimits(min, max, marginPercentage?, marginPercentageTolerance?): Range

Computes rounded limits using margin percentages as constraints.<br> <br> This function tries to compute a 'smart' range that includes the given min/max.<br> To do so it will try to simplify the decimal part of the given values to the closest value.<br> The original range is always contained in the returned range, meaning that the returned 'low' is lesser than the given min and the returned 'high' is greater than the given max.<br> <br> The given margin parameters will be used to constrain rounding process:<br> <ul> <li>Margin:<br> The margin percentage determines how much margin the algorithm will try to introduce.<br> If the given margin percentage is 10%, then the returned 'high'' will be around:<br> <i>high = max + 10% * (max - min)</i>.<br> </li> <br> <li>Margin tolerance:<br> The margin tolerance percentage determines how much the 'smart rounding' process can change the value computed above.<br> If the given margin percentage is 4%, then the returned 'high' will be in the range:<br> <i>[high - <b>0.02</b> * (max - min), high + <b>0.04</b> * (max - min)]</i>.<br> Note that margin tolerance is applied differently for inner tolerance.<br> <pre> ------------------|-----------<----|--------> max +10% (margin)

-2% +4% (margin tolerance) ------------------|-----------<----|--------> high (before rounding) </pre>

Example

import {MathUtil} from '@int/geotoolkit/util/MathUtil';
// With default margin :
MathUtil.calculateRoundedLimits(347.242, 372.110); // returns Range(345, 374);

// With bigger margin (10%) :
MathUtil.calculateRoundedLimits(347.242, 372.110, 0.10); // returns Range(344, 375);

// With values close to zero :
MathUtil.calculateRoundedLimits(-0.0041, 0.012); // returns Range(-0.005, 0.013);

Parameters

Name Type Description
minnumberThe minimum value to be rounded
maxnumberThe maximum value to be rounded
Optional marginPercentagenumberPercentage of margin desired
Optional marginPercentageTolerancenumberPercentage of margin tolerance desired

Returns

Range

The computed range


clamp

▸ Static clamp(value, min, max): number

Clamp the value to the range

Parameters

Name Type Description
valuenumbercurrent value
minnumberminimum value
maxnumbermaximum value

Returns

number

clamped value


computeStatistics

▸ Static computeStatistics(array): Statistics

Compute Statistics for a collection

Parameters

Name Type Description
arraynumber[]raw number array

Returns

Statistics


degToRad

▸ Static degToRad(deg): number

Convert degree to radians

Parameters

Name Type Description
degnumberThe angle in degrees

Returns

number

The angle in radians


equals

▸ Static equals(v1, v2, epsilon?): boolean

Compare two values with specified precision

Parameters

Name Type Description
v1number1st number to compare
v2number2nd number to compare
Optional epsilonnumberdifference bet 2 numbers to compare

Returns

boolean


findIndex

▸ Static findIndex<T&gt;(value, values, fromIndex?, toIndex?, compareFunction?): number

Uses binary search to find an index of given value. If given value is found, it returns the exact index. If given value is not found it returns ~[next closest index].

Type parameters

Name
T

Parameters

Name Type Description
valueTobject to find
valuesT[]sorted array on objects
Optional fromIndexnumberindex to start the search
Optional toIndexnumberindex to end search scope
Optional compareFunction(x: T, y: T) => number | Ordercompare function that defines the sort order. If omitted, the object type must be number. The second parameter passed to this compareFunction is the value passed to findIndex(). OR the data order. Ascending by default.

Returns

number

▸ Static findIndex<T&gt;(value, values, fromIndex?, toIndex?, compareFunction?): number

Type parameters

Name
T

Parameters

Name Type
valuenumber
valuesT[]
Optional fromIndexnumber
Optional toIndexnumber
Optional compareFunctionOrder | (x: T, y: number) => number

Returns

number


findNiceLimits

▸ Static findNiceLimits(min, max, modelStep, minPadding?, maxPadding?): Limits

Find a "nice" settings based on "Algorithm for Optimal Scaling on a Chart Axis".

Parameters

Name Type Description
minnumberminimum value
maxnumbermaximum value
modelStepnumberdesired model space between ticks
Optional minPaddingbooleanadd step padding at first or not
Optional maxPaddingbooleanadd step padding at the end or not

Returns

Limits

calculated limits


getCentile

▸ Static getCentile(values, centileNum): number

Get centile

Parameters

Name Type Description
valuesnumber[]the percent value
centileNumnumberpercentile

Returns

number


getLimits

▸ Static getLimits(arr, init?, nullvalue?): number[]

Return the min and max values of a given array.<br> This function ignores NaN and null values.

Parameters

Name Type Description
arrnumber[]represents the array
Optional initnumber[]represents the initials min and max values: [min, max]
Optional nullvaluenumberA nullvalue to ignore, note that null and NaN are ignored

Returns

number[]

An array containing the [min, max]


getMax

▸ Static getMax(arr, init?, nullvalue?): number

Return the max values of a given array.<br> This function ignores NaN and null values.

Parameters

Name Type Description
arrnumber[]represents the array.
Optional initnumberrepresents the initial max value
Optional nullvaluenumberA nullvalue to ignore, note that null and NaN are ignored

Returns

number

the minimum valid value in the given array.


getMin

▸ Static getMin(arr, init?, nullvalue?): number

Return the min value of a given array. it internally filter NaN and null values.

Parameters

Name Type Description
arrnumber[]represents the array.
Optional initnumberrepresents the initial min value
Optional nullvaluenumberA nullvalue to ignore, note that null and NaN are ignored

Returns

number

the minimum valid value in the given array.


getSeededRandom

▸ Static getSeededRandom(min?, max?, seed?): number

Used for tutorials to create a reproducible random value set.

Parameters

Name Type Description
Optional minnumbervalue of random
Optional maxnumbervalue of random
Optional seednumberseed

Returns

number


getWeightedArithmeticMean

▸ Static getWeightedArithmeticMean(intervals, weights, power?): number

Gets weighted arithmetic mean (or weighted average)

Throws

Error if input arrays are not valid or sum of weights is zero

Parameters

Name Type Description
intervalsnumber[]array of intervals
weightsnumber[]array of their respective weights
Optional powernumberweight power

Returns

number

weighted arithmetic mean


isNumber

▸ Static isNumber(value): value is number

Checks whether value is a finite number.

Parameters

Name Type Description
valueanyvalue to test

Returns

value is number


isNumeric

▸ Static isNumeric(value): value is number

Checks whether value is a finite number.

Parameters

Name Type Description
valueanyvalue to test

Returns

value is number


isPlatformLittleEndian

▸ Static isPlatformLittleEndian(): boolean

Checks if current platform is little endian

Returns

boolean


log10

▸ Static log10(val, precision?, handlenegative?): number

Calculates log base 10

Example

import {MathUtil} from '@int/geotoolkit/util/MathUtil';
MathUtil.log10(-10, null, true); // will give -1 result and MathUtil.log10(-10) will be NaN

Parameters

Name Type Description
valnumbervalue to calculate log base 10
Optional precisionnumberthe number of digits after the decimal point
Optional handlenegativebooleanset true if handling of negative value and 0 is required when mapping

Returns

number


niceNumber

▸ Static niceNumber(value, round?): number

Returns a "nice" number approximately equal to range Rounds the number if round = true takes the ceiling if round = false.

Parameters

Name Type Description
valuenumberinput number
Optional roundbooleanround value

Returns

number

output number


normalizeAngle

▸ Static normalizeAngle(angle): number

Normalizes the provided angle to be in range [0, 2*PI]

Parameters

Name Type Description
anglenumberAngle to normalize

Returns

number


radToDeg

▸ Static radToDeg(rad): number

Convert radians to degree

Parameters

Name Type Description
radnumberThe angle in radians

Returns

number

The angle in degrees


round

▸ Static round(value, base?): number

Rounds value with the provided accuracy base

Example

import {MathUtil} from '@int/geotoolkit/util/MathUtil';
MathUtil.round(12.3456, 1000); // 12.346, rounds to 1/1000 accuracy
MathUtil.round(12.3456, 100); // 12.35, rounds to 1/100 accuracy
MathUtil.round(12.3456, 10); // 12.3, rounds to 1/10 accuracy
MathUtil.round(12.3456, 4); // 12.25, rounds to 1/4 accuracy

Parameters

Name Type Description
valuenumbervalue to round
Optional basenumberaccuracy base to round

Returns

number


roundTo

▸ Static roundTo(src, precision): number

Rounds "src" to relative (see example below) "precision"

Example

import {MathUtil} from '@int/geotoolkit/util/MathUtil';
const a = 0.0000056789;
const resA = MathUtil.roundTo(a, 2); // resA = 0.00000568
const b = 56789.56789;
const resB = MathUtil.roundTo(b, 2); // resB = 56800

Parameters

Name Type Description
srcnumbersource value to be rounded
precisionnumberrelative precision

Returns

number

rounded value


sign

▸ Static sign(a): number

Get sign of specified value

Parameters

Name Type Description
anumbercurrent value

Returns

number

-1 for negative | 0 for zero | +1 for positive