Class MathUtil
A collection of static utility methods for mathematics.
Porting Java class java.lang.Math
and com.devexperts.util.MathUtil
.
public static class MathUtil
- Inheritance
-
MathUtil
- Inherited Members
Methods
Abs(int)
Method like a Abs(int), but not throws OverflowException exception, when argument the argument is equal to the value of MinValue. Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Note that if the argument is equal to the value of MinValue, the most negative representable int value, the result is that same value, which is negative.
public static int Abs(int a)
Parameters
a
intThe argument whose absolute value is to be determined.
Returns
- int
The absolute value of the argument.
Div(int, int)
Returns quotient according to number theory - i.e. when remainder is zero or positive.
public static int Div(int a, int b)
Parameters
Returns
- int
The quotient according to number theory.
FloorDiv(long, long)
Returns the largest (closest to positive infinity) long value that is less than
or equal to the algebraic quotient.
There is one special case, if the dividend is the long.MinValue
and the divisor is -1
,
then integer overflow occurs and the result is equal to the long.MinValue.
Normal integer division operates under the round to zero rounding mode (truncation).
This operation instead acts under the round toward negative infinity (floor) rounding mode.
The floor rounding mode gives different results than truncation when the exact result is negative.
public static long FloorDiv(long x, long y)
Parameters
Returns
- long
The largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
FloorMod(long, long)
Returns the floor modulus of the int arguments.
public static long FloorMod(long x, long y)
Parameters
Returns
- long
The floor modulus:
x - (FloorDiv(x, y) * y)
IsNegativeZero(double)
Checks if the specified number is a -0.0 (negative zero).
public static bool IsNegativeZero(double x)
Parameters
x
doubleThe specified number.
Returns
- bool
Returns
true
if x is equals -0.0.
IsPowerOfTwo(long)
Checks if the specified number is a power of two.
public static bool IsPowerOfTwo(long x)
Parameters
x
longThe specified number.
Returns
- bool
Returns
true
if x represents a power of two.
RoundUpToPowerOf2(uint)
Rounds up the given value to the nearest power of 2.
public static uint RoundUpToPowerOf2(uint value)
Parameters
value
uintThe value to round up.
Returns
- uint
The smallest power of two that's greater than or equal to value. If value is 0 or the result overflows, returns 0.
Remarks
This method uses bit manipulation to round up to the nearest power of 2. The algorithm is based on the "Bit Twiddling Hacks" by Sean Eron Anderson. See: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2