Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Page wiki
View or edit the community-maintained wiki page associated with this page.

# std.math

Elementary mathematical functions

Contains the elementary mathematical functions (powers, roots,
and trigonometric 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.
The following IEEE 'real' formats are currently supported:

- 64 bit Big-endian 'double' (eg PowerPC)
- 128 bit Big-endian 'quadruple' (eg SPARC)
- 64 bit Little-endian 'double' (eg x86-SSE2)
- 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium)
- 128 bit Little-endian 'quadruple' (not implemented on any known processor!)
- Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support

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

License:

Authors:

Source: std/math.d

- real E;
- e = 2.718281...
- real LOG2T;
- log
_{2}10 = 3.321928... - real LOG2E;
- log
_{2}e = 1.442695... - real LOG2;
- log
_{10}2 = 0.301029... - real LOG10E;
- log
_{10}e = 0.434294... - real LN2;
- ln 2 = 0.693147...
- real LN10;
- ln 10 = 2.302585...
- real PI;
- π = 3.141592...
- real PI_2;
- π / 2 = 1.570796...
- real PI_4;
- π / 4 = 0.785398...
- real M_1_PI;
- 1 / π = 0.318309...
- real M_2_PI;
- 2 / π = 0.636619...
- real M_2_SQRTPI;
- 2 / √π = 1.128379...
- real SQRT2;
- √2 = 1.414213...
- real SQRT1_2;
- √½ = 0.707106...
- pure nothrow @safe Num abs(Num)(Num
*x*) if (is(typeof(Num.init >= 0)) && is(typeof(-Num.init)) && !(is(Num* : const(ifloat*)) || is(Num* : const(idouble*)) || is(Num* : const(ireal*))));

pure nothrow @nogc @safe real abs(Num)(Num*y*) if (is(Num* : const(ifloat*)) || is(Num* : const(idouble*)) || is(Num* : const(ireal*))); - Calculates the absolute value
- pure nothrow @nogc @safe creal conj(creal
*z*);

pure nothrow @nogc @safe ireal conj(ireal*y*); - Complex conjugate
- pure nothrow @nogc @safe real cos(real
*x*); - Returns cosine of
*x*.*x*is in radians.Bugs:Results are undefined if |*x*| >= 2^{64}. - pure nothrow @nogc @safe real sin(real
*x*); - Returns sine of
*x*.*x*is in radians.Bugs:Results are undefined if |*x*| >= 2^{64}. - pure nothrow @nogc @safe creal sin(creal
*z*);

pure nothrow @nogc @safe ireal sin(ireal*y*); - sine, complex and imaginary
- pure nothrow @nogc @safe creal cos(creal
*z*);

pure nothrow @nogc @safe real cos(ireal*y*); - cosine, complex and imaginary
- pure nothrow @nogc @trusted real tan(real
*x*); - Returns tangent of
*x*.*x*is in radians. - pure nothrow @nogc @safe real acos(real
*x*);

pure nothrow @nogc @safe double acos(double*x*);

pure nothrow @nogc @safe float acos(float*x*); - Calculates the arc cosine of
*x*, returning a value ranging from 0 to π. - pure nothrow @nogc @safe real asin(real
*x*);

pure nothrow @nogc @safe double asin(double*x*);

pure nothrow @nogc @safe float asin(float*x*); - Calculates the arc sine of
*x*, returning a value ranging from -π/2 to π/2. - pure nothrow @nogc @safe real atan(real
*x*);

pure nothrow @nogc @safe double atan(double*x*);

pure nothrow @nogc @safe float atan(float*x*); - Calculates the arc tangent of
*x*, returning a value ranging from -π/2 to π/2. - pure nothrow @nogc @trusted real atan2(real
*y*, real*x*);

pure nothrow @nogc @safe double atan2(double*y*, double*x*);

pure nothrow @nogc @safe float atan2(float*y*, float*x*); - 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 - pure nothrow @nogc @safe real cosh(real
*x*);

pure nothrow @nogc @safe double cosh(double*x*);

pure nothrow @nogc @safe float cosh(float*x*); - Calculates the hyperbolic cosine of
*x*. - pure nothrow @nogc @safe real sinh(real
*x*);

pure nothrow @nogc @safe double sinh(double*x*);

pure nothrow @nogc @safe float sinh(float*x*); - Calculates the hyperbolic sine of
*x*. - pure nothrow @nogc @safe real tanh(real
*x*);

pure nothrow @nogc @safe double tanh(double*x*);

pure nothrow @nogc @safe float tanh(float*x*); - Calculates the hyperbolic tangent of
*x*. - pure nothrow @nogc @safe real acosh(real
*x*);

pure nothrow @nogc @safe double acosh(double*x*);

pure nothrow @nogc @safe float acosh(float*x*); - Calculates the inverse hyperbolic cosine of
*x*. - pure nothrow @nogc @safe real asinh(real
*x*);

pure nothrow @nogc @safe double asinh(double*x*);

pure nothrow @nogc @safe float asinh(float*x*); - Calculates the inverse hyperbolic sine of
*x*. - pure nothrow @nogc @safe real atanh(real
*x*);

pure nothrow @nogc @safe double atanh(double*x*);

pure nothrow @nogc @safe float atanh(float*x*); - Calculates the inverse hyperbolic tangent of
*x*, returning a value from ranging from -1 to 1. - pure nothrow @nogc @safe long rndtol(real
*x*); - 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. - real rndtonl(real
*x*); - 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. - pure nothrow @nogc @safe float sqrt(float
*x*);

pure nothrow @nogc @safe double sqrt(double*x*);

pure nothrow @nogc @safe real sqrt(real*x*); - Compute square root of
*x*. - pure nothrow @nogc @trusted real exp(real
*x*);

pure nothrow @nogc @safe double exp(double*x*);

pure nothrow @nogc @safe float exp(float*x*); - Calculates e
*x*.Special Values *x*e *x*+∞ +∞ -∞ +0.0 NAN NAN - pure nothrow @nogc @trusted real expm1(real
*x*); - Calculates the value of the natural logarithm base (e) raised to the power of
*x*, minus 1. - pure nothrow @nogc @trusted real exp2(real
*x*); - Calculates 2
*x*. - pure nothrow @nogc @trusted creal expi(real
*y*); - 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. - pure nothrow @nogc @trusted real frexp(real
*value*, out int*exp*); - 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 - nothrow @nogc @trusted int ilogb(real
*x*); - Extracts the exponent of
*x*as a signed integral value. - pure nothrow @nogc @safe real ldexp(real
*n*, int*exp*); - Compute
*n** 2*exp*References: frexp

- pure nothrow @nogc @safe real log(real
*x*); - Calculate the natural logarithm of
*x*. - pure nothrow @nogc @safe real log10(real
*x*); - Calculate the base-10 logarithm of
*x*. - pure nothrow @nogc @safe real log1p(real
*x*); - Calculates the natural logarithm of 1 +
*x*. - pure nothrow @nogc @safe real log2(real
*x*); - Calculates the base-2 logarithm of
*x*: log_{2}*x* - nothrow @nogc @trusted real logb(real
*x*); - Extracts the exponent of
*x*as a signed integral value. - nothrow @nogc @trusted real fmod(real
*x*, real*y*); - Calculates the remainder from the calculation
*x*/*y*. - nothrow @nogc @trusted real modf(real
*x*, ref real*i*); - 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*. - nothrow @nogc @trusted real scalbn(real
*x*, int*n*); - Efficiently calculates
*x** 2*n*. - nothrow @nogc @trusted real cbrt(real
*x*); - Calculates the cube root of
*x*. - pure nothrow @nogc @safe real fabs(real
*x*); - Returns |
*x*| - pure nothrow @nogc @safe real hypot(real
*x*, real*y*); - 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*: - pure nothrow @nogc @trusted real ceil(real
*x*); - Returns the value of
*x*rounded upward to the next integer (toward positive infinity). - pure nothrow @nogc @trusted real floor(real
*x*); - Returns the value of
*x*rounded downward to the next integer (toward negative infinity). - nothrow @nogc @trusted real nearbyint(real
*x*); - Rounds
*x*to the nearest integer value, using the current rounding mode. - pure nothrow @nogc @safe real rint(real
*x*); - 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. - pure nothrow @nogc @trusted long lrint(real
*x*); - Rounds
*x*to the nearest integer value, using the current rounding mode. - nothrow @nogc @trusted real round(real
*x*); - 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. - nothrow @nogc @trusted long lround(real
*x*); - 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. - nothrow @nogc @trusted real trunc(real
*x*); - Returns the integer portion of
*x*, dropping the fractional portion.This is also known as "chop" rounding. - nothrow @nogc @trusted real remainder(real
*x*, real*y*);

nothrow @nogc @trusted real remquo(real*x*, real*y*, out int*n*); -
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

- struct IeeeFlags;
- 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);

- @property bool inexact();
- The result cannot be represented exactly, so rounding occurred.(example: x = sin(0.1); )
- @property bool underflow();
- @property bool overflow();
- @property bool divByZero();
- An infinity was generated by division by zero (example: x = 3/0.0; )
- @property bool invalid();
- A machine NaN was generated. (example: x = real.infinity * 0.0; )

- void resetIeeeFlags();
- Set all of the floating-point status flags to
**false**. - @property IeeeFlags ieeeFlags();
- Return a snapshot of the current state of the floating-point status flags.
- struct FloatingPointControl;
- Control the Floating point hardwareChange 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:

{ FloatingPointControl fpctrl; // Enable hardware exceptions for division by zero, overflow to infinity, // invalid operations, and uninitialized floating-point variables. fpctrl.enableExceptions(FloatingPointControl.severeExceptions); // This will generate a hardware exception, if x is a // default-initialized floating point variable: real x; // Add `= 0` or even `= real.nan` to not throw the exception. real y = x * 3.0; // The exception is only thrown for default-uninitialized NaN-s. // NaN-s with other payload are valid: real z = y * real.nan; // ok // Changing the rounding mode: fpctrl.rounding = FloatingPointControl.roundUp; assert(rint(1.1) == 2); // The set hardware exceptions will be disabled when leaving this scope. // The original rounding mode will also be restored. } // Ensure previous values are returned: assert(!FloatingPointControl.enabledExceptions); assert(FloatingPointControl.rounding == FloatingPointControl.roundToNearest); assert(rint(1.1) == 1);

- severeExceptions
- Severe = The overflow, division by zero, and invalid exceptions.
- static nothrow @nogc @property @safe bool hasExceptionTraps();
- Returns
**true**if the current FPU supports exception trapping - @nogc void enableExceptions(uint
*exceptions*); - Enable (unmask) specific hardware
*exceptions*. Multiple*exceptions*may be ORed together. - @nogc void disableExceptions(uint
*exceptions*); - Disable (mask) specific hardware
*exceptions*. Multiple*exceptions*may be ORed together. - @nogc @property void rounding(RoundingMode
*newMode*); - static @nogc @property uint enabledExceptions();
- Return the exceptions which are currently enabled (unmasked)
- static @nogc @property RoundingMode rounding();

- pure nothrow @nogc @trusted bool isNaN(X)(X
*x*) if (isFloatingPoint!X); - Returns !=0 if e is a NaN.
- pure nothrow @nogc @trusted int isFinite(X)(X
*e*); - Returns !=0 if e is finite (not infinite or NAN).
- pure nothrow @nogc @trusted int isNormal(X)(X
*x*); - Returns !=0 if x is normalized (not zero, subnormal, infinite, or NAN).
- pure nothrow @nogc @trusted int isSubnormal(X)(X
*x*); - Is number subnormal? (Also called "denormal".) Subnormals have a 0 exponent and a 0 most significant mantissa bit.
- pure nothrow @nogc @trusted bool isInfinity(X)(X
*x*) if (isFloatingPoint!X); - Return !=0 if e is ±∞.
- pure nothrow @nogc @trusted bool isIdentical(real
*x*, real*y*); - 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'. - pure nothrow @nogc @trusted int signbit(X)(X
*x*); - Return 1 if sign bit of e is set, 0 if not.
- pure nothrow @nogc @trusted R copysign(R, X)(R
*to*, X*from*) if (isFloatingPoint!R && isFloatingPoint!X); - Return a value composed of to with from's sign bit.
- pure nothrow @nogc @safe F sgn(F)(F
*x*); - Returns -1 if x < 0, x if x == 0, 1 if x > 0, and NAN if x==NAN.
- pure nothrow @nogc @trusted real NaN(ulong
*payload*); - 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. - pure nothrow @nogc @trusted ulong getNaNPayload(real
*x*); - 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.
- pure nothrow @nogc @trusted real nextUp(real
*x*);

pure nothrow @nogc @trusted double nextUp(double*x*);

pure nothrow @nogc @trusted float nextUp(float*x*); - Calculate the next largest floating point value after
*x*. - pure nothrow @nogc @safe real nextDown(real
*x*);

pure nothrow @nogc @safe double nextDown(double*x*);

pure nothrow @nogc @safe float nextDown(float*x*); - Calculate the next smallest floating point value before
*x*. - pure nothrow @nogc @safe T nextafter(T)(T
*x*, T*y*); - 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. - pure nothrow @nogc @safe real fdim(real
*x*, real*y*); - Returns the positive difference between
*x*and*y*. - pure nothrow @nogc @safe real fmax(real
*x*, real*y*); - Returns the larger of
*x*and*y*. - pure nothrow @nogc @safe real fmin(real
*x*, real*y*); - Returns the smaller of
*x*and*y*. - pure nothrow @nogc @safe real fma(real
*x*, real*y*, real*z*); - Returns (
*x***y*) +*z*, rounding only once according to the current rounding mode.Bugs:Not currently implemented - rounds twice. - pure nothrow @nogc @trusted Unqual!F pow(F, G)(F
*x*, G*n*) if (isFloatingPoint!F && isIntegral!G); - Compute the value of x n, where n is an integer
- pure nothrow @nogc @trusted typeof(Unqual!F.init * Unqual!G.init) pow(F, G)(F
*x*, G*n*) if (isIntegral!F && isIntegral!G); - 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.
- pure nothrow @nogc @trusted real pow(I, F)(I
*x*, F*y*) if (isIntegral!I && isFloatingPoint!F); - Computes integer to floating point powers.
- pure nothrow @nogc @trusted Unqual!(Largest!(F, G)) pow(F, G)(F
*x*, G*y*) if (isFloatingPoint!F && isFloatingPoint!G); - Calculates xy.
- pure nothrow @nogc @trusted int feqrel(X)(X
*x*, X*y*) if (isFloatingPoint!X); - To what precision is x equal to y?
- pure nothrow @nogc @trusted real poly(real
*x*, const real[]*A*); - 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 *x*the value to evaluate. real[] *A*array of coefficients a _{0}, a_{1}, etc. - bool approxEqual(T, U, V)(T
*lhs*, U*rhs*, V*maxRelDiff*, V*maxAbsDiff*= 1e-05); - Computes whether lhs is approximately equal to rhs admitting a maximum relative difference maxRelDiff and a maximum absolute difference maxAbsDiff.
- bool approxEqual(T, U)(T
*lhs*, U*rhs*);