# std.math

Elementary mathematical functions Contains the elementary mathematical functions (powers, roots, and trignometric functions), and low-level floating-point operations. Mathematical special functions are available in std.mathspecial. The functionality closely follows the IEEE754-2008 standard for floating-point arithmetic, including the use of camelCase names rather than C99-style lower case names. All of these functions behave correctly when presented with an infinity or NaN. Unlike C, there is no global 'errno' variable. Consequently, almost all of these functions are pure nothrow.**Status:**

The semantics and names of feqrel and approxEqual will be revised.

**Source:**

std/math.d

**License:**

Boost License 1.0.

**Authors:**

Walter Bright, Don Clugston

**Source:**

std/math.d

- e = 2.718281...
- log
_{2}10 = 3.321928... - log
_{2}e = 1.442695... - log
_{10}2 = 0.301029... - log
_{10}e = 0.434294... - ln 2 = 0.693147...
- ln 10 = 2.302585...
- π = 3.141592...
- π / 2 = 1.570796...
- π / 4 = 0.785398...
- 1 / π = 0.318309...
- 2 / π = 0.636619...
- 2 / √π = 1.128379...
- √2 = 1.414213...
- √½ = 0.707106...
- Calculates the absolute value
For complex numbers,
__abs__(z) = sqrt( z.re^{2}+ z.im^{2}) = hypot(z.re, z.im). - Complex conjugate
__conj__(x + iy) = x - iy Note that*z**__conj__(*z*) =*z*.re^{2}-*z*.im^{2}is always a real number - Returns cosine of
*x*.*x*is in radians.Special Values *x*__cos__(*x*)invalid? NAN NAN yes ±∞ NAN yes

Results are undefined if |*x*| >= 2^{64}. - Returns sine of
*x*.*x*is in radians.Special Values *x*__sin__(*x*)invalid? NAN NAN yes ±0.0 ±0.0 no ±∞ NAN yes

Results are undefined if |*x*| >= 2^{64}. - sine, complex and imaginary
__sin__(*z*) =__sin__(*z*.re)*cosh(*z*.im) + cos(*z*.re)*sinh(*z*.im)i If both__sin__(θ) and cos(θ) are required, it is most efficient to use expi(θ). - cosine, complex and imaginary
__cos__(*z*) =__cos__(*z*.re)*cosh(*z*.im) - sin(*z*.re)*sinh(*z*.im)i - Returns tangent of
*x*.*x*is in radians.Special Values *x*__tan__(*x*)invalid? NAN NAN yes ±0.0 ±0.0 no ±∞ NAN yes - Calculates the arc cosine of
*x*, returning a value ranging from 0 to π.Special Values *x*__acos__(*x*)invalid? >1.0 NAN yes <-1.0 NAN yes NAN NAN yes - Calculates the arc sine of
*x*, returning a value ranging from -π/2 to π/2.Special Values *x*__asin__(*x*)invalid? ±0.0 ±0.0 no >1.0 NAN yes <-1.0 NAN yes - Calculates the arc tangent of
*x*, returning a value ranging from -π/2 to π/2.Special Values *x*__atan__(*x*)invalid? ±0.0 ±0.0 no ±∞ NAN yes - Calculates the arc tangent of
*y*/*x*, returning a value ranging from -π to π.Special Values *y**x*atan( *y*,*x*)NAN anything NAN anything NAN NAN ±0.0 >0.0 ±0.0 ±0.0 +0.0 ±0.0 ±0.0 <0.0 ±π ±0.0 -0.0 ±π >0.0 ±0.0 π/2 <0.0 ±0.0 -π/2 >0.0 ∞ ±0.0 ±∞ anything ±π/2 >0.0 -∞ ±π ±∞ ∞ ±π/4 ±∞ -∞ ±3π/4 - Calculates the hyperbolic cosine of
*x*.Special Values *x*__cosh__(*x*)invalid? ±∞ ±0.0 no - Calculates the hyperbolic sine of
*x*.Special Values *x*__sinh__(*x*)invalid? ±0.0 ±0.0 no ±∞ ±∞ no - Calculates the hyperbolic tangent of
*x*.Special Values *x*__tanh__(*x*)invalid? ±0.0 ±0.0 no ±∞ ±1.0 no - Calculates the inverse hyperbolic cosine of
*x*. Mathematically,__acosh__(*x*) = log(*x*+ sqrt(*x***x*- 1))Special Values *x*__acosh__(*x*)NAN NAN <1 NAN 1 0 +∞ +∞ - Calculates the inverse hyperbolic sine of
*x*. Mathematically,asinh(x) = log( x + sqrt( x*x + 1 )) // if x >= +0 asinh(x) = -log(-x + sqrt( x*x + 1 )) // if x <= -0

Special Values *x*__asinh__(*x*)NAN NAN ±0 ±0 ±∞ ±∞ - Calculates the inverse hyperbolic tangent of
*x*, returning a value from ranging from -1 to 1. Mathematically,__atanh__(*x*) = log( (1+*x*)/(1-*x*) ) / 2Special Values *x*acosh( *x*)NAN NAN ±0 ±0 -∞ -0 - Returns
*x*rounded to a long value using the current rounding mode. If the integer value of*x*is greater than long.max, the result is indeterminate. - Returns
*x*rounded to a long value using the FE_TONEAREST rounding mode. If the integer value of*x*is greater than long.max, the result is indeterminate. - Compute square root of
*x*.Special Values *x*__sqrt__(*x*)invalid? -0.0 -0.0 no <0.0 NAN yes +∞ +∞ no - Calculates e
*x*.Special Values *x*e *x*+∞ +∞ -∞ +0.0 NAN NAN - Calculates the value of the natural logarithm base (e)
raised to the power of
*x*, minus 1. For very small*x*,__expm1__(*x*) is more accurate than exp(*x*)-1.Special Values *x*e *x*-1±0.0 ±0.0 +∞ +∞ -∞ -1.0 NAN NAN - Calculates 2
*x*.Special Values *x*__exp2__(*x*)+∞ +∞ -∞ +0.0 NAN NAN - Calculate cos(
*y*) + i sin(*y*). On many CPUs (such as x86), this is a very efficient operation; almost twice as fast as calculating sin(*y*) and cos(*y*) separately, and is the preferred method when both are required. - Separate floating point
*value*into significand and exponent.**Returns:**

Calculate and return*x*andsuch that*exp**value*=*x**2*exp*and .5 <= |*x*| < 1.0*x*has same sign as*value*.Special Values *value*returns *exp*±0.0 ±0.0 0 +∞ +∞ int.max -∞ -∞ int.min ±NAN ±NAN int.min - Extracts the exponent of
*x*as a signed integral value. If*x*is not a special value, the result is the same as cast(int)logb(*x*).Special Values *x*__ilogb__(*x*)Range error? 0 FP_ILOGB0 yes ±∞ int.max no NAN FP_ILOGBNAN no - Compute
*n** 2*exp***References:**

frexp - Calculate the natural logarithm of
*x*.Special Values *x*__log__(*x*)divide by 0? invalid? ±0.0 -∞ yes no <0.0 NAN no yes +∞ +∞ no no - Calculate the base-10 logarithm of
*x*.Special Values *x*__log10__(*x*)divide by 0? invalid? ±0.0 -∞ yes no <0.0 NAN no yes +∞ +∞ no no - Calculates the natural logarithm of 1 +
*x*. For very small*x*,__log1p__(*x*) will be more accurate than log(1 +*x*).Special Values *x*__log1p__(*x*)divide by 0? invalid? ±0.0 ±0.0 no no -1.0 -∞ yes no <-1.0 NAN no yes +∞ -∞ no no - Calculates the base-2 logarithm of
*x*: log_{2}*x*Special Values *x*__log2__(*x*)divide by 0? invalid? ±0.0 -∞ yes no <0.0 NAN no yes +∞ +∞ no no - Extracts the exponent of
*x*as a signed integral value. If*x*is subnormal, it is treated as if it were normalized. For a positive, finite*x*: 1 <=* FLT_RADIX-*x*__logb__(*x*) < FLT_RADIXSpecial Values *x*__logb__(*x*)divide by 0? ±∞ +∞ no ±0.0 -∞ yes - Calculates the remainder from the calculation
*x*/*y*.**Returns:**

The value of*x*- i **y*, where i is the number of times that*y*can be completely subtracted from*x*. The result has the same sign as*x*.Special Values *x**y*__fmod__(*x*,*y*)invalid? ±0.0 not 0.0 ±0.0 no ±∞ anything NAN yes anything ±0.0 NAN yes !=±∞ ±∞ *x*no - Breaks
*x*into an integral part and a fractional part, each of which has the same sign as*x*. The integral part is stored in*i*.**Returns:**

The fractional part of*x*.Special Values *x**i*(on input)__modf__(*x*,*i*)*i*(on return)±∞ anything ±0.0 ±∞ - Efficiently calculates
*x** 2*n*.__scalbn__handles underflow and overflow in the same fashion as the basic arithmetic operators.Special Values *x*scalb( *x*)±∞ ±∞ ±0.0 ±0.0 - Calculates the cube root of
*x*.Special Values *x*__cbrt__(*x*)invalid? ±0.0 ±0.0 no NAN NAN yes ±∞ ±∞ no - Returns |
*x*|Special Values *x*__fabs__(*x*)±0.0 +0.0 ±∞ +∞ - Calculates the length of the
hypotenuse of a right-angled triangle with sides of length
*x*and*y*. The hypotenuse is the value of the square root of the sums of the squares of*x*and*y*: sqrt(*x*^{2}+*y*^{2}) Note that__hypot__(*x*,*y*),__hypot__(*y*,*x*) and__hypot__(*x*, -*y*) are equivalent.Special Values *x**y*__hypot__(*x*,*y*)invalid? *x*±0.0 | *x*|no ±∞ *y*+∞ no ±∞ NAN +∞ no - Returns the value of
*x*rounded upward to the next integer (toward positive infinity). - Returns the value of
*x*rounded downward to the next integer (toward negative infinity). - Rounds
*x*to the nearest integer value, using the current rounding mode. Unlike the rint functions,__nearbyint__does not raise the FE_INEXACT exception. - Rounds
*x*to the nearest integer value, using the current rounding mode. If the return value is not equal to*x*, the FE_INEXACT exception is raised.**nearbyint**performs the same operation, but does not set the FE_INEXACT exception. - Rounds
*x*to the nearest integer value, using the current rounding mode. This is generally the fastest method to convert a floating-point number to an integer. Note that the results from this function depend on the rounding mode, if the fractional part of*x*is exactly 0.5. If using the default rounding mode (ties round to even integers)__lrint__(4.5) == 4,__lrint__(5.5)==6. - Return the value of
*x*rounded to the nearest integer. If the fractional part of*x*is exactly 0.5, the return value is rounded to the even integer. - Return the value of
*x*rounded to the nearest integer. If the fractional part of*x*is exactly 0.5, the return value is rounded away from zero. - Returns the integer portion of
*x*, dropping the fractional portion. This is also known as "chop" rounding. - Calculate the
__remainder__*x*REM*y*, following IEC 60559. REM is the value of*x*-*y** n, where n is the integer nearest the exact value of*x*/*y*. If |n -*x*/*y*| == 0.5, n is even. If the result is zero, it has the same sign as*x*. Otherwise, the sign of the result is the sign of*x*/*y*. Precision mode has no effect on the__remainder__functions. remquo returns n in the parameter n.Special Values *x**y*__remainder__(*x*,*y*)n invalid? ±0.0 not 0.0 ±0.0 0.0 no ±∞ anything NAN ? yes anything ±0.0 NAN ? yes != ±∞ ±∞ *x*? no **Note:**

remquo not supported on windows - IEEE exception status flags ('sticky bits')
These flags indicate that an exceptional floating-point condition has occurred.
They indicate that a NaN or an infinity has been generated, that a result
is inexact, or that a signalling NaN has been encountered. If floating-point
exceptions are enabled (unmasked), a hardware exception will be generated
instead of setting these flags.
**Example:**

real a=3.5; // Set all the flags to zero resetIeeeFlags(); assert(!ieeeFlags.divByZero); // Perform a division by zero. a/=0.0L; assert(a==real.infinity); assert(ieeeFlags.divByZero); // Create a NaN a*=0.0L; assert(ieeeFlags.invalid); assert(isNaN(a)); // Check that calling func() has no effect on the // status flags. IeeeFlags f = ieeeFlags; func(); assert(ieeeFlags == f);

- The result cannot be represented exactly, so rounding occured. (example: x = sin(0.1); )
- A zero was generated by
__underflow__(example: x = real.min*real.epsilon/2;) - An infinity was generated by
__overflow__(example: x = real.max*2;) - An infinity was generated by division by zero (example: x = 3/0.0; )
- A machine NaN was generated. (example: x = real.infinity * 0.0; )

- Set all of the floating-point status flags to
**false**. - Return a snapshot of the current state of the floating-point status flags.
- Control the Floating point hardware
Change the IEEE754 floating-point rounding mode and the floating-point
hardware exceptions.
By default, the rounding mode is roundToNearest and all hardware exceptions
are disabled. For most applications, debugging is easier if the
*division by zero*,*overflow*, and*invalid operation*exceptions are enabled. These three are combined into a*severeExceptions*value for convenience. Note in particular that if*invalidException*is enabled, a hardware trap will be generated whenever an uninitialized floating-point variable is used. All changes are temporary. The previous state is restored at the end of the scope.**Example:**

{ // Enable hardware exceptions for division by zero, overflow to infinity, // invalid operations, and uninitialized floating-point variables. FloatingPointControl fpctrl; fpctrl.enableExceptions(FloatingPointControl.severeExceptions); double y = x*3.0; // will generate a hardware exception, if x is uninitialized. // fpctrl.rounding = FloatingPointControl.roundUp; // The hardware exceptions will be disabled when leaving this scope. // The original rounding mode will also be restored. }

- Severe = The overflow, division by zero, and invalid exceptions.
- Enable (unmask) specific hardware
*exceptions*. Multiple*exceptions*may be ORed together. - Disable (mask) specific hardware
*exceptions*. Multiple*exceptions*may be ORed together. - Change the floating-point hardware
__rounding__mode - Return the exceptions which are currently enabled (unmasked)
- Return the currently active
__rounding__mode

- Returns !=0 if e is a NaN.
- Returns !=0 if
*e*is finite (not infinite or NAN). - Returns !=0 if x is normalized (not zero, subnormal, infinite, or NAN).
- Is number subnormal? (Also called "denormal".) Subnormals have a 0 exponent and a 0 most significant mantissa bit.
- Return !=0 if e is ±∞.
- Is the binary representation of
*x*identical to*y*? Same as ==, except that positive and negative zero are not identical, and two NANs are identical if they have the same 'payload'. - Return 1 if sign bit of e is set, 0 if not.
- Return a value composed of
*to*with*from*'s sign bit. - Returns -1 if x < 0, x if x == 0, 1 if x > 0, and NAN if x==NAN.
- Create a quiet NAN, storing an integer inside the
*payload*. For floats, the largest possible*payload*is 0x3F_FFFF. For doubles, it is 0x3_FFFF_FFFF_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF. - Extract an integral payload from a NAN.
**Returns:**

the integer payload as a ulong. For floats, the largest possible payload is 0x3F_FFFF. For doubles, it is 0x3_FFFF_FFFF_FFFF. For 80-bit or 128-bit reals, it is 0x3FFF_FFFF_FFFF_FFFF. - Calculate the next largest floating point value after
*x*. Return the least number greater than*x*that is representable as a real; thus, it gives the next point on the IEEE number line.Special Values *x*__nextUp__(*x*)-∞ -real.max ±0.0 real.min_normal*real.epsilon real.max ∞ ∞ ∞ NAN NAN - Calculate the next smallest floating point value before
*x*. Return the greatest number less than*x*that is representable as a real; thus, it gives the previous point on the IEEE number line.Special Values *x*__nextDown__(*x*)∞ real.max ±0.0 -real.min_normal*real.epsilon -real.max -∞ -∞ -∞ NAN NAN - Calculates the next representable value after x in the direction of y.
If y > x, the result will be the next largest floating-point value;
if y < x, the result will be the next smallest value.
If x == y, the result is y.
**Remarks:**

This function is not generally very useful; it's almost always better to use the faster functions nextUp() or nextDown() instead. The FE_INEXACT and FE_OVERFLOW exceptions will be raised if x is finite and the function result is infinite. The FE_INEXACT and FE_UNDERFLOW exceptions will be raised if the function value is subnormal, and x is not equal to y. - Returns the positive difference between
*x*and*y*.**Returns:**Special Values *x*,*y*__fdim__(*x*,*y*)*x*>*y**x*-*y**x*<=*y*+0.0 - Returns the larger of
*x*and*y*. - Returns the smaller of
*x*and*y*. - Returns (
*x***y*) +*z*, rounding only once according to the current rounding mode. BUGS:

Not currently implemented - rounds twice. - Compute the value of x n, where n is an integer
- Compute the value of an integer x, raised to the power of a positive integer n. If both x and n are 0, the result is 1. If n is negative, an integer divide error will occur at runtime, regardless of the value of x.
- Computes integer to floating point powers.
- Calculates xy.
- To what precision is x equal to y?
**Returns:**

the number of mantissa bits which are equal in x and y. eg, 0x1.F8p+60 and 0x1.F1p+60 are equal to 5 bits of precision.Special Values x y __feqrel__(x, y)x x real.mant_dig x >= 2*x 0 x <= x/2 0 NAN any 0 any NAN 0 - Evaluate polynomial
*A*(*x*) = a_{0}+ a_{1}*x*+ a_{2}*x*^{2}+ a_{3}*x*^{3}; ... Uses Horner's rule*A*(*x*) = a_{0}+*x*(a_{1}+*x*(a_{2}+*x*(a_{3}+ ...)))**Parameters:**real[] *A*array of coefficients a _{0}, a_{1}, etc. - Computes whether lhs is approximately equal to rhs
admitting a maximum relative difference maxRelDiff and a
maximum absolute difference maxAbsDiff.
If the two inputs are ranges,
__approxEqual__returns**true**if and only if the ranges have the same number of elements and if__approxEqual__evaluates to**true**for each pair of elements. - Returns
__approxEqual__(lhs, rhs, 1e-2, 1e-5).