API / geotoolkit / util / MathUtil / MathUtil
The class Math contains methods for performing basic numeric operations and basic algorithms.
Constructors
Methods
Accessors
• Static get epsilon(): number
constant for epsilon equal to 1E-10
number
• Static get logMin(): number
constant for minimum logarithmic value to be display equal to 1E-10
number
• Static get quickSort(): (array: any[] | number[], lo: number, hi: number, comparator: Comparator, swap: Swap) => void
Quick sort (in-place).
fn
▸ (array, lo, hi, comparator, swap): void
Quick sort (in-place).
| Name | Type | Description |
|---|---|---|
array | any[] | number[] | array of numbers or objects |
lo | number | starting index |
hi | number | ending index (including) |
comparator | Comparator | optional 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. |
swap | Swap | optional swap function to swap two elements of collection, like: function(array, i, j) { } |
void
• Static get sortPointsClockwise(): (xArray: number[], yArray: number[], isClockwise?: boolean) => void
Sort given array clockwise around their center point.
fn
▸ (xArray, yArray, isClockwise?): void
Sort given array clockwise around their center point.
| Name | Type | Description |
|---|---|---|
xArray | number[] | x-coordinate of points |
yArray | number[] | y-coordinate of points |
Optional isClockwise | boolean |
void
Methods
▸ 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.
| Name | Type | Description |
|---|---|---|
first | Point | first point |
p1 | Point | control point #1 |
p2 | Point | control point #2 |
last | Point | last point |
Optional flatness | number | precision |
Point[]
array of interpolated points if "param" is undefined or is an Array instance
▸ 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.
To do so, it will compute a minimum and maximum that can be easily divided by 2.
Which means the user will immediately guess the mid and quarter values.
The purpose of this function is not to provide accurately rounded limits but limits that will be easily apprehended.
Using the given limits can virtually remove the necessity of displaying the intermediates labels on a axis.
For example it will return [0, 4000] for the values [790, 3050].
The user will easily guess the mid value to be 2000.
| Name | Type | Description |
|---|---|---|
min | number | The minimum value |
max | number | The maximum value |
Optional logScale | boolean | If this should use a logarithmic scale instead of linear |
Optional centerOnZeroOnNegativeMin | boolean | If this should center the limits around 0 if minimum is a negative value |
Optional splitOnZero | boolean | If this should split neat limits result around 0, applicable only when Math.sign(minimum) != Math.sign(maximum) |
The computed neat limits
▸ Static calculateNiceLimits(min, max, desiredNumberOfTicks, minPadding?, maxPadding?): Limits
Create a "nice" range based on "Algorithm for Optimal Scaling on a Chart Axis".
| Name | Type | Description |
|---|---|---|
min | number | minimum value |
max | number | maximum value |
desiredNumberOfTicks | number | desired number of ticks |
Optional minPadding | boolean | add step padding at first or not |
Optional maxPadding | boolean | add step padding at the end or not |
calculated limits
▸ Static calculateRoundedLimits(min, max, marginPercentage?, marginPercentageTolerance?): Range
Computes rounded limits using margin percentages as constraints.
This function tries to compute a 'smart' range that includes the given min/max.
To do so it will try to simplify the decimal part of the given values to the closest value.
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.
The given margin parameters will be used to constrain rounding process:
- Margin:
The margin percentage determines how much margin the algorithm will try to introduce.
If the given margin percentage is 10%, then the returned 'high'' will be around:
high = max + 10% * (max - min). - Margin tolerance:
The margin tolerance percentage determines how much the 'smart rounding' process can change the value computed above.
If the given margin percentage is 4%, then the returned 'high' will be in the range:
[high - 0.02 * (max - min), high + 0.04 * (max - min)].
Note that margin tolerance is applied differently for inner tolerance.------------------|-----------<----|--------> max +10% (margin)
-2% +4% (margin tolerance) ------------------|-----------<----|--------> high (before rounding)
Exampleimport {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);Name Type Description minnumberThe minimum value to be rounded maxnumberThe maximum value to be rounded OptionalmarginPercentagenumberPercentage of margin desired OptionalmarginPercentageTolerancenumberPercentage of margin tolerance desired The computed range
▸
Staticclamp(value,min,max):numberClamp the value to the range
Name Type Description valuenumbercurrent value minnumberminimum value maxnumbermaximum value numberclamped value
▸
StaticcomputeStatistics(array):StatisticsCompute Statistics for a collection
Name Type Description arraynumber[]raw number array ▸
StaticdegToRad(deg):numberConvert degree to radians
Name Type Description degnumberThe angle in degrees numberThe angle in radians
▸
Staticequals(v1,v2,epsilon?):booleanCompare two values with specified precision
Name Type Description v1number1st number to compare v2number2nd number to compare Optionalepsilonnumberdifference bet 2 numbers to compare boolean▸
StaticfindIndex<T>(value,values,fromIndex?,toIndex?,compareFunction?):numberUses 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].
Name TName Type Description valueTobject to find valuesT[]sorted array on objects OptionalfromIndexnumberindex to start the search OptionaltoIndexnumberindex to end search scope OptionalcompareFunction( 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. number▸
StaticfindIndex<T>(value,values,fromIndex?,toIndex?,compareFunction?):numberName TName Type valuenumbervaluesT[]OptionalfromIndexnumberOptionaltoIndexnumberOptionalcompareFunctionOrder| (x:T,y:number) =>numbernumber▸
StaticfindNiceLimits(min,max,modelStep,minPadding?,maxPadding?):LimitsFind a "nice" settings based on "Algorithm for Optimal Scaling on a Chart Axis".
Name Type Description minnumberminimum value maxnumbermaximum value modelStepnumberdesired model space between ticks OptionalminPaddingbooleanadd step padding at first or not OptionalmaxPaddingbooleanadd step padding at the end or not calculated limits
▸
StaticgetCentile(values,centileNum):numberGet centile
Name Type Description valuesnumber[]the percent value centileNumnumberpercentile number▸
StaticgetLimits(arr,init?,nullvalue?):number[]Return the min and max values of a given array.
This function ignores NaN and null values.Name Type Description arrnumber[]represents the array Optionalinitnumber[]represents the initials min and max values: [min, max] OptionalnullvaluenumberA nullvalue to ignore, note that null and NaN are ignored number[]An array containing the [min, max]
▸
StaticgetMax(arr,init?,nullvalue?):numberReturn the max values of a given array.
This function ignores NaN and null values.Name Type Description arrnumber[]represents the array. Optionalinitnumberrepresents the initial max value OptionalnullvaluenumberA nullvalue to ignore, note that null and NaN are ignored numberthe minimum valid value in the given array.
▸
StaticgetMin(arr,init?,nullvalue?):numberReturn the min value of a given array. it internally filter NaN and null values.
Name Type Description arrnumber[]represents the array. Optionalinitnumberrepresents the initial min value OptionalnullvaluenumberA nullvalue to ignore, note that null and NaN are ignored numberthe minimum valid value in the given array.
▸
StaticgetSeededRandom(min?,max?,seed?):numberUsed for tutorials to create a reproducible random value set.
Name Type Description Optionalminnumbervalue of random Optionalmaxnumbervalue of random Optionalseednumberseed number▸
StaticgetWeightedArithmeticMean(intervals,weights,power?):numberGets weighted arithmetic mean (or weighted average)
ThrowsError if input arrays are not valid or sum of weights is zero
Name Type Description intervalsnumber[]array of intervals weightsnumber[]array of their respective weights Optionalpowernumberweight power numberweighted arithmetic mean
▸
StaticisNumber(value): value is numberChecks whether value is a finite number.
Name Type Description valueanyvalue to test value is number
▸
StaticisNumeric(value): value is numberChecks whether value is a finite number.
Name Type Description valueanyvalue to test value is number
▸
StaticisPlatformLittleEndian():booleanChecks if current platform is little endian
boolean▸
Staticlog10(val,precision?,handlenegative?):numberCalculates log base 10
Exampleimport {MathUtil} from '@int/geotoolkit/util/MathUtil'; MathUtil.log10(-10, null, true); // will give -1 result and MathUtil.log10(-10) will be NaNName Type Description valnumbervalue to calculate log base 10 Optionalprecisionnumberthe number of digits after the decimal point Optionalhandlenegativebooleanset true if handling of negative value and 0 is required when mapping number▸
StaticniceNumber(value,round?):numberReturns a "nice" number approximately equal to range Rounds the number if round = true takes the ceiling if round = false.
Name Type Description valuenumberinput number Optionalroundbooleanround value numberoutput number
▸
StaticnormalizeAngle(angle):numberNormalizes the provided angle to be in range [0, 2*PI]
Name Type Description anglenumberAngle to normalize number▸
StaticradToDeg(rad):numberConvert radians to degree
Name Type Description radnumberThe angle in radians numberThe angle in degrees
▸
Staticround(value,base?):numberRounds value with the provided accuracy base
Exampleimport {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 accuracyName Type Description valuenumbervalue to round Optionalbasenumberaccuracy base to round number▸
StaticroundTo(src,precision):numberRounds "src" to relative (see example below) "precision"
Exampleimport {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 = 56800Name Type Description srcnumbersource value to be rounded precisionnumberrelative precision numberrounded value
▸
Staticsign(a):numberGet sign of specified value
Name Type Description anumbercurrent value number-1 for negative | 0 for zero | +1 for positive