BinaryFloatingPoint

protocol BinaryFloatingPoint

A radix-2 (binary) floating-point type.

The BinaryFloatingPoint protocol extends the FloatingPoint protocol with operations specific to floating-point binary types, as defined by the IEEE 754 specification. BinaryFloatingPoint is implemented in the standard library by Float, Double, and Float80 where available.

See Also: FloatingPoint

Inheritance AbsoluteValuable, Comparable, Equatable, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, FloatingPoint, SignedNumber, Strideable View Protocol Hierarchy →
Associated Types
RawSignificand : UnsignedInteger

A type that can represent the encoded significand of a value.

RawExponent : UnsignedInteger

A type that can represent the encoded exponent of a value.

FloatLiteralType

A type that can represent a floating-point literal.

Valid types for FloatLiteralType are Float, Double, and Float80 where available.

IntegerLiteralType
Exponent : SignedInteger

A type that can represent any written exponent.

Stride : SignedNumber

A type that can represent the distance between two values of Self.

Import import Swift

Initializers

init(_: Double) Required

Creates a new instance from the given value, rounded to the closest possible representation.

value: A floating-point value.

Declaration

init(_ value: Double)
init(_: Float) Required

Creates a new instance from the given value, rounded to the closest possible representation.

value: A floating-point value.

Declaration

init(_ value: Float)
init(_: Float80) Required

Creates a new instance from the given value, rounded to the closest possible representation.

value: A floating-point value.

Declaration

init(_ value: Float80)
init(sign:exponentBitPattern:significandBitPattern:) Required

Creates a new instance from the specified sign and bit patterns.

The values passed as exponentBitPattern and significandBitPattern are interpreted in the binary interchange format defined by the IEEE 754 specification.

Parameters: sign: The sign of the new value. exponentBitPattern: The bit pattern to use for the exponent field of the new value. significandBitPattern: The bit pattern to use for the significand field of the new value.

Declaration

init(sign: FloatingPointSign, exponentBitPattern: Self.RawExponent, significandBitPattern: Self.RawSignificand)
init(floatLiteral:) Required

Creates an instance initialized to the specified floating-point value.

Declaration

init(floatLiteral value: Self.FloatLiteralType)

Declared In

ExpressibleByFloatLiteral
init(integerLiteral:) Required

Create an instance initialized to value.

Declaration

init(integerLiteral value: Self.IntegerLiteralType)

Declared In

ExpressibleByIntegerLiteral
init(_: Int) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: Int)

Declared In

FloatingPoint
init(_: Int8) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: Int8)

Declared In

FloatingPoint
init(_: Int16) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: Int16)

Declared In

FloatingPoint
init(_: Int32) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: Int32)

Declared In

FloatingPoint
init(_: Int64) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: Int64)

Declared In

FloatingPoint
init(_: UInt) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: UInt)

Declared In

FloatingPoint
init(_: UInt8) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: UInt8)

Declared In

FloatingPoint
init(_: UInt16) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: UInt16)

Declared In

FloatingPoint
init(_: UInt32) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: UInt32)

Declared In

FloatingPoint
init(_: UInt64) Required

Creates a new value, rounded to the closest possible representatation.

If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern.

value: The integer to convert to a floating-point value.

Declaration

init(_ value: UInt64)

Declared In

FloatingPoint
init(sign:exponent:significand:) Required

Creates a new value from the given sign, exponent, and significand.

The following example uses this initializer to create a new Double instance. Double is a binary floating-point type that has a radix of 2.

let x = Double(sign: .plus, exponent: -2, significand: 1.5)
// x == 0.375

This initializer is equivalent to the following calculation, where ** is exponentation, computed as if by a single, correctly rounded, floating-point operation:

let sign: FloatingPointSign = .plus
let exponent = -2
let significand = 1.5
let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent
// y == 0.375

As with any basic operation, if this value is outside the representable range of the type, overflow or underflow occurs, and zero, a subnormal value, or infinity may result. In addition, there are two other edge cases:

  • If the value you pass to significand is zero or infinite, the result is zero or infinite, regardless of the value of exponent.
  • If the value you pass to significand is NaN, the result is NaN.

For any floating-point value x of type F, the result of the following is equal to x, with the distinction that the result is canonicalized if x is in a noncanonical encoding:

let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand)

This initializer implements the scaleB operation defined by the IEEE 754 specification.

Parameters: sign: The sign to use for the new value. exponent: The new value's exponent. significand: The new value's significand.

Declaration

init(sign: FloatingPointSign, exponent: Self.Exponent, significand: Self)

Declared In

FloatingPoint
init(signOf:magnitudeOf:)

Creates a new floating-point value using the sign of one value and the magnitude of another.

The following example uses this initializer to create a new Double instance with the sign of a and the magnitude of b:

let a = -21.5
let b = 305.15
let c = Double(signOf: a, magnitudeOf: b)
print(c)
// Prints "-305.15"

This initializer implements the IEEE 754 copysign operation.

Parameters: signOf: A value from which to use the sign. The result of the initializer has the same sign as signOf. magnitudeOf: A value from which to use the magnitude. The result of the initializer has the same magnitude as magnitudeOf.

Declaration

init(signOf: Self, magnitudeOf: Self)

Declared In

FloatingPoint

Static Variables

static var exponentBitCount: Int Required

The number of bits used to represent the type's exponent.

A binary floating-point type's exponentBitCount imposes a limit on the range of the exponent for normal, finite values. The exponent bias of a type F can be calculated as the following, where ** is exponentation:

let bias = 2 ** (F.exponentBitCount - 1) - 1

The least normal exponent for values of the type F is 1 - bias, and the largest finite exponent is bias. An all-zeros exponent is reserved for subnormals and zeros, and an all-ones exponent is reserved for infinity and NaN.

For example, the Float type has an exponentBitCount of 8, which gives an exponent bias of 127 by the calculation above.

let bias = 2 ** (Float.exponentBitCount - 1) - 1
// bias == 127
print(Float.greatestFiniteMagnitude.exponent)
// Prints "127"
print(Float.leastNormalMagnitude.exponent)
// Prints "-126"

Declaration

static var exponentBitCount: Int { get }
static var significandBitCount: Int Required

The available number of fractional significand bits.

For fixed-width floating-point types, this is the actual number of fractional significand bits.

For extensible floating-point types, significandBitCount should be the maximum allowed significand width (without counting any leading integral bit of the significand). If there is no upper limit, then significandBitCount should be Int.max.

Note that Float80.significandBitCount is 63, even though 64 bits are used to store the significand in the memory representation of a Float80 (unlike other floating-point types, Float80 explicitly stores the leading integral significand bit, but the BinaryFloatingPoint APIs provide an abstraction so that users don't need to be aware of this detail).

Declaration

static var significandBitCount: Int { get }
static var greatestFiniteMagnitude: Self Required

The greatest finite number representable by this type.

This value compares greater than or equal to all finite numbers, but less than infinity.

This value corresponds to type-specific C macros such as FLT_MAX and DBL_MAX. The naming of those macros is slightly misleading, because infinity is greater than this value.

Declaration

static var greatestFiniteMagnitude: Self { get }

Declared In

FloatingPoint
static var infinity: Self Required

Positive infinity.

Infinity compares greater than all finite numbers and equal to other infinite values.

let x = Double.greatestFiniteMagnitude
let y = x * 2
// y == Double.infinity
// y > x

Declaration

static var infinity: Self { get }

Declared In

FloatingPoint
static var leastNonzeroMagnitude: Self Required

The least positive number.

This value compares less than or equal to all positive numbers, but greater than zero. If the type supports subnormal values, leastNonzeroMagnitude is smaller than leastNormalMagnitude; otherwise they are equal.

Declaration

static var leastNonzeroMagnitude: Self { get }

Declared In

FloatingPoint
static var leastNormalMagnitude: Self Required

The least positive normal number.

This value compares less than or equal to all positive normal numbers. There may be smaller positive numbers, but they are subnormal, meaning that they are represented with less precision than normal numbers.

This value corresponds to type-specific C macros such as FLT_MIN and DBL_MIN. The naming of those macros is slightly misleading, because subnormals, zeros, and negative numbers are smaller than this value.

Declaration

static var leastNormalMagnitude: Self { get }

Declared In

FloatingPoint
static var nan: Self Required

A quiet NaN ("not a number").

A NaN compares not equal, not greater than, and not less than every value, including itself. Passing a NaN to an operation generally results in NaN.

let x = 1.21
// x > Double.nan == false
// x < Double.nan == false
// x == Double.nan == false

Because a NaN always compares not equal to itself, to test whether a floating-point value is NaN, use its isNaN property instead of the equal-to operator (==). In the following example, y is NaN.

let y = x + Double.nan
print(y == Double.nan)
// Prints "false"
print(y.isNaN)
// Prints "true"

See Also: isNaN, signalingNaN

Declaration

static var nan: Self { get }

Declared In

FloatingPoint
static var pi: Self Required

The mathematical constant pi.

This value should be rounded toward zero to keep user computations with angles from inadvertently ending up in the wrong quadrant. A type that conforms to the FloatingPoint protocol provides the value for pi at its best possible precision.

print(Double.pi)
// Prints "3.14159265358979"

Declaration

static var pi: Self { get }

Declared In

FloatingPoint
static var radix: Int

The radix, or base of exponentiation, for a floating-point type.

The magnitude of a floating-point value x of type F can be calculated by using the following formula, where ** is exponentiation:

let magnitude = x.significand * F.radix ** x.exponent

A conforming type may use any integer radix, but values other than 2 (for binary floating-point types) or 10 (for decimal floating-point types) are extraordinarily rare in practice.

Declaration

static var radix: Int { get }

Declared In

FloatingPoint
static var signalingNaN: Self Required

A signaling NaN ("not a number").

The default IEEE 754 behavior of operations involving a signaling NaN is to raise the Invalid flag in the floating-point environment and return a quiet NaN.

Operations on types conforming to the FloatingPoint protocol should support this behavior, but they might also support other options. For example, it would be reasonable to implement alternative operations in which operating on a signaling NaN triggers a runtime error or results in a diagnostic for debugging purposes. Types that implement alternative behaviors for a signaling NaN must document the departure.

Other than these signaling operations, a signaling NaN behaves in the same manner as a quiet NaN.

See Also: nan

Declaration

static var signalingNaN: Self { get }

Declared In

FloatingPoint
static var ulpOfOne: Self

The unit in the last place of 1.0.

The positive difference between 1.0 and the next greater representable number. The ulpOfOne constant corresponds to the C macros FLT_EPSILON, DBL_EPSILON, and others with a similar purpose.

Declaration

static var ulpOfOne: Self { get }

Declared In

FloatingPoint

Instance Variables

var binade: Self Required

The floating-point value with the same sign and exponent as this value, but with a significand of 1.0.

A binade is a set of binary floating-point values that all have the same sign and exponent. The binade property is a member of the same binade as this value, but with a unit significand.

In this example, x has a value of 21.5, which is stored as 1.34375 * 2**4, where ** is exponentiation. Therefore, x.binade is equal to 1.0 * 2**4, or 16.0.

let x = 21.5
// x.significand == 1.34375
// x.exponent == 4

let y = x.binade
// y == 16.0
// y.significand == 1.0
// y.exponent == 4

Declaration

var binade: Self { get }
var exponentBitPattern: Self.RawExponent Required

The raw encoding of the value's exponent field.

This value is unadjusted by the type's exponent bias.

See Also: exponentBitCount

Declaration

var exponentBitPattern: Self.RawExponent { get }
var significandBitPattern: Self.RawSignificand Required

The raw encoding of the value's significand field.

The significandBitPattern property does not include the leading integral bit of the significand, even for types like Float80 that store it explicitly.

Declaration

var significandBitPattern: Self.RawSignificand { get }
var significandWidth: Int Required

The number of bits required to represent the value's significand.

If this value is a finite nonzero number, significandWidth is the number of fractional bits required to represent the value of significand; otherwise, significandWidth is -1. The value of significandWidth is always -1 or between zero and significandBitCount. For example:

  • For any representable power of two, significandWidth is zero, because significand is 1.0.
  • If x is 10, x.significand is 1.01 in binary, so x.significandWidth is 2.
  • If x is Float.pi, x.significand is 1.10010010000111111011011 in binary, and x.significandWidth is 23.

Declaration

var significandWidth: Int { get }
var exponent: Self.Exponent Required

The exponent of the floating-point value.

The exponent of a floating-point value is the integer part of the logarithm of the value's magnitude. For a value x of a floating-point type F, the magnitude can be calculated as the following, where ** is exponentiation:

let magnitude = x.significand * F.radix ** x.exponent

In the next example, y has a value of 21.5, which is encoded as 1.34375 * 2 ** 4. The significand of y is therefore 1.34375.

let y: Double = 21.5
// y.significand == 1.34375
// y.exponent == 4
// Double.radix == 2

The exponent property has the following edge cases:

  • If x is zero, then x.exponent is Int.min.
  • If x is +/-infinity or NaN, then x.exponent is Int.max

This property implements the logB operation defined by the IEEE 754 specification.

Declaration

var exponent: Self.Exponent { get }

Declared In

FloatingPoint
var floatingPointClass: FloatingPointClassification

The classification of this value.

A value's floatingPointClass property describes its "class" as described by the IEEE 754 specification.

Declaration

var floatingPointClass: FloatingPointClassification { get }

Declared In

FloatingPoint
var isCanonical: Bool Required

A Boolean value indicating whether the instance's representation is in the canonical form.

The IEEE 754 specification defines a canonical, or preferred, encoding of a floating-point value's representation. Every Float or Double value is canonical, but noncanonical values of the Float80 type exist, and noncanonical values may exist for other types that conform to the FloatingPoint protocol.

Declaration

var isCanonical: Bool { get }

Declared In

FloatingPoint
var isFinite: Bool Required

A Boolean value indicating whether this instance is finite.

All values other than NaN and infinity are considered finite, whether normal or subnormal.

Declaration

var isFinite: Bool { get }

Declared In

FloatingPoint
var isInfinite: Bool Required

A Boolean value indicating whether the instance is infinite.

Note that isFinite and isInfinite do not form a dichotomy, because they are not total: If x is NaN, then both properties are false.

Declaration

var isInfinite: Bool { get }

Declared In

FloatingPoint
var isNaN: Bool Required

A Boolean value indicating whether the instance is NaN ("not a number").

Because NaN is not equal to any value, including NaN, use this property instead of the equal-to operator (==) or not-equal-to operator (!=) to test whether a value is or is not NaN. For example:

let x = 0.0
let y = x * .infinity
// y is a NaN

// Comparing with the equal-to operator never returns 'true'
print(x == Double.nan)
// Prints "false"
print(y == Double.nan)
// Prints "false"

// Test with the 'isNaN' property instead
print(x.isNaN)
// Prints "false"
print(y.isNaN)
// Prints "true"

This property is true for both quiet and signaling NaNs.

Declaration

var isNaN: Bool { get }

Declared In

FloatingPoint
var isNormal: Bool Required

A Boolean value indicating whether this instance is normal.

A normal value is a finite number that uses the full precision available to values of a type. Zero is neither a normal nor a subnormal number.

Declaration

var isNormal: Bool { get }

Declared In

FloatingPoint
var isSignalingNaN: Bool Required

A Boolean value indicating whether the instance is a signaling NaN.

Signaling NaNs typically raise the Invalid flag when used in general computing operations.

Declaration

var isSignalingNaN: Bool { get }

Declared In

FloatingPoint
var isSubnormal: Bool Required

A Boolean value indicating whether the instance is subnormal.

A subnormal value is a nonzero number that has a lesser magnitude than the smallest normal number. Subnormal values do not use the full precision available to values of a type.

Zero is neither a normal nor a subnormal number. Subnormal numbers are often called denormal or denormalized---these are different names for the same concept.

Declaration

var isSubnormal: Bool { get }

Declared In

FloatingPoint
var isZero: Bool Required

A Boolean value indicating whether the instance is equal to zero.

The isZero property of a value x is true when x represents either -0.0 or +0.0. x.isZero is equivalent to the following comparison: x == 0.0.

let x = -0.0
x.isZero        // true
x == 0.0        // true

Declaration

var isZero: Bool { get }

Declared In

FloatingPoint
var nextDown: Self

The greatest representable value that compares less than this value.

For any finite value x, x.nextDown is greater than x. For nan or -infinity, x.nextDown is x itself. The following special cases also apply:

  • If x is infinity, then x.nextDown is greatestFiniteMagnitude.
  • If x is leastNonzeroMagnitude, then x.nextDown is 0.0.
  • If x is zero, then x.nextDown is -leastNonzeroMagnitude.
  • If x is -greatestFiniteMagnitude, then x.nextDown is -infinity.

Declaration

var nextDown: Self { get }

Declared In

FloatingPoint
var nextUp: Self Required

The least representable value that compares greater than this value.

For any finite value x, x.nextUp is greater than x. For nan or infinity, x.nextUp is x itself. The following special cases also apply:

  • If x is -infinity, then x.nextUp is -greatestFiniteMagnitude.
  • If x is -leastNonzeroMagnitude, then x.nextUp is -0.0.
  • If x is zero, then x.nextUp is leastNonzeroMagnitude.
  • If x is greatestFiniteMagnitude, then x.nextUp is infinity.

Declaration

var nextUp: Self { get }

Declared In

FloatingPoint
var sign: FloatingPointSign Required

The sign of the floating-point value.

The sign property is .minus if the value's signbit is set, and .plus otherwise. For example:

let x = -33.375
// x.sign == .minus

Don't use this property to check whether a floating point value is negative. For a value x, the comparison x.sign == .minus is not necessarily the same as x < 0. In particular, x.sign == .minus if x is -0, and while x < 0 is always false if x is NaN, x.sign could be either .plus or .minus.

Declaration

var sign: FloatingPointSign { get }

Declared In

FloatingPoint
var significand: Self Required

The significand of the floating-point value.

The magnitude of a floating-point value x of type F can be calculated by using the following formula, where ** is exponentiation:

let magnitude = x.significand * F.radix ** x.exponent

In the next example, y has a value of 21.5, which is encoded as 1.34375 * 2 ** 4. The significand of y is therefore 1.34375.

let y: Double = 21.5
// y.significand == 1.34375
// y.exponent == 4
// Double.radix == 2

If a type's radix is 2, then for finite nonzero numbers, the significand is in the range 1.0 ..< 2.0. For other values of x, x.significand is defined as follows:

  • If x is zero, then x.significand is 0.0.
  • If x is infinity, then x.significand is 1.0.
  • If x is NaN, then x.significand is NaN. Note: The significand is frequently also called the mantissa, but significand is the preferred terminology in the IEEE 754 specification, to allay confusion with the use of mantissa for the fractional part of a logarithm.

Declaration

var significand: Self { get }

Declared In

FloatingPoint
var ulp: Self Required

The unit in the last place of self.

This is the unit of the least significant digit in the significand of self. For most numbers x, this is the difference between x and the next greater (in magnitude) representable number. There are some edge cases to be aware of:

  • greatestFiniteMagnitude.ulp is a finite number, even though the next greater representable value is infinity.
  • x.ulp is NaN if x is not a finite number.
  • If x is very small in magnitude, then x.ulp may be a subnormal number. On targets that do not support subnormals, x.ulp may be rounded to zero.

This quantity, or a related quantity, is sometimes called epsilon or machine epsilon. Avoid that name because it has different meanings in different languages, which can lead to confusion, and because it suggests that it is a good tolerance to use for comparisons, which it almost never is.

Declaration

var ulp: Self { get }

Declared In

FloatingPoint

Static Methods

static func abs(_:) Required

Returns the absolute value of x.

Declaration

static func abs(_ x: Self) -> Self

Declared In

AbsoluteValuable
static func maximum(_:_:)

Returns the greater of the two given values.

This method returns the maximum of two values, preserving order and eliminating NaN when possible. For two values x and y, the result of maximum(x, y) is x if x > y, y if x <= y, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.maximum(10.0, -25.0)
// 10.0
Double.maximum(10.0, .nan)
// 10.0
Double.maximum(.nan, -25.0)
// -25.0
Double.maximum(.nan, .nan)
// nan

The maximum method implements the maxNum operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: The greater of x and y, or whichever is a number if the other is NaN.

Declaration

static func maximum(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func maximumMagnitude(_:_:)

Returns the value with greater magnitude.

This method returns the value with greater magnitude of the two given values, preserving order and eliminating NaN when possible. For two values x and y, the result of maximumMagnitude(x, y) is x if x.magnitude > y.magnitude, y if x.magnitude <= y.magnitude, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.maximumMagnitude(10.0, -25.0)
// -25.0
Double.maximumMagnitude(10.0, .nan)
// 10.0
Double.maximumMagnitude(.nan, -25.0)
// -25.0
Double.maximumMagnitude(.nan, .nan)
// nan

The maximumMagnitude method implements the maxNumMag operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: Whichever of x or y has greater magnitude, or whichever is a number if the other is NaN.

Declaration

static func maximumMagnitude(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func minimum(_:_:)

Returns the lesser of the two given values.

This method returns the minimum of two values, preserving order and eliminating NaN when possible. For two values x and y, the result of minimum(x, y) is x if x <= y, y if y < x, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.minimum(10.0, -25.0)
// -25.0
Double.minimum(10.0, .nan)
// 10.0
Double.minimum(.nan, -25.0)
// -25.0
Double.minimum(.nan, .nan)
// nan

The minimum method implements the minNum operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: The minimum of x and y, or whichever is a number if the other is NaN.

Declaration

static func minimum(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func minimumMagnitude(_:_:)

Returns the value with lesser magnitude.

This method returns the value with lesser magnitude of the two given values, preserving order and eliminating NaN when possible. For two values x and y, the result of minimumMagnitude(x, y) is x if x.magnitude <= y.magnitude, y if y.magnitude < x.magnitude, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.minimumMagnitude(10.0, -25.0)
// 10.0
Double.minimumMagnitude(10.0, .nan)
// 10.0
Double.minimumMagnitude(.nan, -25.0)
// -25.0
Double.minimumMagnitude(.nan, .nan)
// nan

The minimumMagnitude method implements the minNumMag operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: Whichever of x or y has lesser magnitude, or whichever is a number if the other is NaN.

Declaration

static func minimumMagnitude(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint

Instance Methods

func <(_:rhs:) Required

Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.

This function is the only requirement of the Comparable protocol. The remainder of the relational operator functions are implemented by the standard library for any type that conforms to Comparable.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func <(lhs: Self, rhs: Self) -> Bool

Declared In

Comparable
func <=(_:rhs:)

Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func <=(lhs: Self, rhs: Self) -> Bool

Declared In

Comparable
func ==(_:rhs:) Required

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func ==(lhs: Self, rhs: Self) -> Bool

Declared In

Equatable
func >(_:rhs:)

Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func >(lhs: Self, rhs: Self) -> Bool

Declared In

Comparable
func >=(_:rhs:)

Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func >=(lhs: Self, rhs: Self) -> Bool

Declared In

Comparable
prefix func -(_:) Required

Returns the result of negating x.

Declaration

prefix func -(x: Self) -> Self

Declared In

SignedNumber
func -(_:rhs:) Required

Returns the difference between lhs and rhs.

Declaration

func -(lhs: Self, rhs: Self) -> Self

Declared In

SignedNumber
mutating func add(_:) Required

Adds the given value to this value in place, rounded to a representable value.

This method serves as the basis for the in-place addition operator (+=). For example:

var (x, y) = (2.25, 2.25)
x.add(7.0)
// x == 9.25
y += 7.0
// y == 9.25

other: The value to add.

See Also: adding(_:)

Declaration

mutating func add(_ other: Self)

Declared In

FloatingPoint
mutating func addProduct(_:_:) Required

Adds the product of the two given values to this value in place, computed without intermediate rounding.

Parameters: lhs: One of the values to multiply before adding to this value. rhs: The other value to multiply.

Declaration

mutating func addProduct(_ lhs: Self, _ rhs: Self)

Declared In

FloatingPoint
func adding(_:)

Returns the sum of this value and the given value, rounded to a representable value.

This method serves as the basis for the addition operator (+). For example:

let x = 1.5
print(x.adding(2.25))
// Prints "3.75"
print(x + 2.25)
// Prints "3.75"

The adding(_:) method implements the addition operation defined by the IEEE 754 specification.

other: The value to add. Returns: The sum of this value and other, rounded to a representable value.

See Also: add(_:)

Declaration

func adding(_ other: Self) -> Self

Declared In

FloatingPoint
func addingProduct(_:_:)

Returns the result of adding the product of the two given values to this value, computed without intermediate rounding.

This method is equivalent to the C fma function and implements the fusedMultiplyAdd operation defined by the IEEE 754 specification.

Parameters: lhs: One of the values to multiply before adding to this value. rhs: The other value to multiply. Returns: The product of lhs and rhs, added to this value.

Declaration

func addingProduct(_ lhs: Self, _ rhs: Self) -> Self

Declared In

FloatingPoint
func advanced(by:) Required

Returns a Self x such that self.distance(to: x) approximates n.

If Stride conforms to Integer, then self.distance(to: x) == n.

Complexity: O(1).

Declaration

func advanced(by n: Self.Stride) -> Self

Declared In

Strideable
func distance(to:) Required

Returns a stride x such that self.advanced(by: x) approximates other.

If Stride conforms to Integer, then self.advanced(by: x) == other.

Complexity: O(1).

Declaration

func distance(to other: Self) -> Self.Stride

Declared In

Strideable
mutating func divide(by:) Required

Divides this value by the given value in place, rounding to a representable value.

This method serves as the basis for the in-place division operator (/=). For example:

var (x, y) = (16.875, 16.875)
x.divide(by: 2.25)
// x == 7.5
y /= 2.25
// y == 7.5

other: The value to use when dividing this value.

See Also: divided(by:)

Declaration

mutating func divide(by other: Self)

Declared In

FloatingPoint
func divided(by:)

Returns the quotient of this value and the given value, rounded to a representable value.

This method serves as the basis for the division operator (/). For example:

let x = 7.5
let y = x.divided(by: 2.25)
// y == 16.875
let z = x * 2.25
// z == 16.875

The divided(by:) method implements the division operation defined by the IEEE 754 specification.

other: The value to use when dividing this value. Returns: The quotient of this value and other, rounded to a representable value.

See Also: divide(by:)

Declaration

func divided(by other: Self) -> Self

Declared In

FloatingPoint
mutating func formRemainder(dividingBy:) Required

Replaces this value with the remainder of itself divided by the given value.

For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.

The following example calculates the remainder of dividing 8.625 by 0.75:

var x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.toNearestOrEven)
// q == 12.0
x.formRemainder(dividingBy: 0.75)
// x == -0.375

let x1 = 0.75 * q + x
// x1 == 8.625

If this value and other are finite numbers, the remainder is in the closed range -abs(other / 2)...abs(other / 2). The remainder(dividingBy:) method is always exact.

other: The value to use when dividing this value.

See Also: remainder(dividingBy:), formTruncatingRemainder(dividingBy:)

Declaration

mutating func formRemainder(dividingBy other: Self)

Declared In

FloatingPoint
mutating func formSquareRoot() Required

Replaces this value with its square root, rounded to a representable value.

See Also: sqrt(_:), squareRoot()

Declaration

mutating func formSquareRoot()

Declared In

FloatingPoint
mutating func formTruncatingRemainder(dividingBy:) Required

Replaces this value with the remainder of itself divided by the given value using truncating division.

Performing truncating division with floating-point values results in a truncated integer quotient and a remainder. For values x and y and their truncated integer quotient q, the remainder r satisfies x == y * q + r.

The following example calculates the truncating remainder of dividing 8.625 by 0.75:

var x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.towardZero)
// q == 11.0
x.formTruncatingRemainder(dividingBy: 0.75)
// x == 0.375

let x1 = 0.75 * q + x
// x1 == 8.625

If this value and other are both finite numbers, the truncating remainder has the same sign as other and is strictly smaller in magnitude. The formtruncatingRemainder(dividingBy:) method is always exact.

other: The value to use when dividing this value.

See Also: truncatingRemainder(dividingBy:), formRemainder(dividingBy:)

Declaration

mutating func formTruncatingRemainder(dividingBy other: Self)

Declared In

FloatingPoint
func isEqual(to:) Required

Returns a Boolean value indicating whether this instance is equal to the given value.

This method serves as the basis for the equal-to operator (==) for floating-point values. When comparing two values with this method, -0 is equal to +0. NaN is not equal to any value, including itself. For example:

let x = 15.0
x.isEqual(to: 15.0)
// true
x.isEqual(to: .nan)
// false
Double.nan.isEqual(to: .nan)
// false

The isEqual(to:) method implements the equality predicate defined by the IEEE 754 specification.

other: The value to compare with this value. Returns: true if other has the same value as this instance; otherwise, false.

Declaration

func isEqual(to other: Self) -> Bool

Declared In

FloatingPoint
func isLess(than:) Required

Returns a Boolean value indicating whether this instance is less than the given value.

This method serves as the basis for the less-than operator (<) for floating-point values. Some special cases apply:

  • Because NaN compares not less than nor greater than any value, this method returns false when called on NaN or when NaN is passed as other.
  • -infinity compares less than all values except for itself and NaN.
  • Every value except for NaN and +infinity compares less than +infinity.

    let x = 15.0 x.isLess(than: 20.0) // true x.isLess(than: .nan) // false Double.nan.isLess(than: x) // false

The isLess(than:) method implements the less-than predicate defined by the IEEE 754 specification.

other: The value to compare with this value. Returns: true if other is less than this value; otherwise, false.

Declaration

func isLess(than other: Self) -> Bool

Declared In

FloatingPoint
func isLessThanOrEqualTo(_:) Required

Returns a Boolean value indicating whether this instance is less than or equal to the given value.

This method serves as the basis for the less-than-or-equal-to operator (<=) for floating-point values. Some special cases apply:

  • Because NaN is incomparable with any value, this method returns false when called on NaN or when NaN is passed as other.
  • -infinity compares less than or equal to all values except NaN.
  • Every value except NaN compares less than or equal to +infinity.

    let x = 15.0 x.isLessThanOrEqualTo(20.0) // true x.isLessThanOrEqualTo(.nan) // false Double.nan.isLessThanOrEqualTo(x) // false

The isLessThanOrEqualTo(_:) method implements the less-than-or-equal predicate defined by the IEEE 754 specification.

other: The value to compare with this value. Returns: true if other is less than this value; otherwise, false.

Declaration

func isLessThanOrEqualTo(_ other: Self) -> Bool

Declared In

FloatingPoint
func isTotallyOrdered(belowOrEqualTo:)

Returns a Boolean value indicating whether this instance should precede the given value in an ascending sort.

This relation is a refinement of the less-than-or-equal-to operator (<=) that provides a total order on all values of the type, including noncanonical encodings, signed zeros, and NaNs. Because it is used much less frequently than the usual comparisons, there is no operator form of this relation.

The following example uses isTotallyOrdered(below:) to sort an array of floating-point values, including some that are NaN:

var numbers = [2.5, 21.25, 3.0, .nan, -9.5]
numbers.sort { $0.isTotallyOrdered(below: $1) }
// numbers == [-9.5, 2.5, 3.0, 21.25, nan]

The isTotallyOrdered(belowOrEqualTo:) method implements the total order relation as defined by the IEEE 754 specification.

other: A floating-point value to compare to this value. Returns: true if this value is ordered below other in a total ordering of the floating-point type; otherwise, false.

Declaration

func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool

Declared In

FloatingPoint
func multiplied(by:)

Returns the product of this value and the given value, rounded to a representable value.

This method serves as the basis for the multiplication operator (*). For example:

let x = 7.5
print(x.multiplied(by: 2.25))
// Prints "16.875"
print(x * 2.25)
// Prints "16.875"

The multiplied(by:) method implements the multiplication operation defined by the IEEE 754 specification.

other: The value to multiply by this value. Returns: The product of this value and other, rounded to a representable value.

See Also: multiply(by:)

Declaration

func multiplied(by other: Self) -> Self

Declared In

FloatingPoint
mutating func multiply(by:) Required

Multiplies this value by the given value in place, rounding to a representable value.

This method serves as the basis for the in-place multiplication operator (*=). For example:

var (x, y) = (7.5, 7.5)
x.multiply(by: 2.25)
// x == 16.875
y *= 2.25
// y == 16.875

other: The value to multiply by this value.

See Also: multiplied(by:)

Declaration

mutating func multiply(by other: Self)

Declared In

FloatingPoint
mutating func negate() Required

Replaces this value with its additive inverse.

The result is always exact. This example uses the negate() method to negate the value of the variable x:

var x = 21.5
x.negate()
// x == -21.5

See Also: negated()

Declaration

mutating func negate()

Declared In

FloatingPoint
func negated()

Returns the additive inverse of this value.

The result is always exact. This method serves as the basis for the negation operator (prefixed -). For example:

let x = 21.5
let y = x.negated()
// y == -21.5

Returns: The additive inverse of this value.

See Also: negate()

Declaration

func negated() -> Self

Declared In

FloatingPoint
func remainder(dividingBy:)

Returns the remainder of this value divided by the given value.

For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.

The following example calculates the remainder of dividing 8.625 by 0.75:

let x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.toNearestOrEven)
// q == 12.0
let r = x.remainder(dividingBy: 0.75)
// r == -0.375

let x1 = 0.75 * q + r
// x1 == 8.625

If this value and other are finite numbers, the remainder is in the closed range -abs(other / 2)...abs(other / 2). The remainder(dividingBy:) method is always exact. This method implements the remainder operation defined by the IEEE 754 specification.

other: The value to use when dividing this value. Returns: The remainder of this value divided by other.

See Also: formRemainder(dividingBy:), truncatingRemainder(dividingBy:)

Declaration

func remainder(dividingBy other: Self) -> Self

Declared In

FloatingPoint
mutating func round(_:) Required

Rounds the value to an integral value using the specified rounding rule.

The following example rounds a value using four different rounding rules:

// Equivalent to the C 'round' function:
var w = 6.5
w.round(.toNearestOrAwayFromZero)
// w == 7.0

// Equivalent to the C 'trunc' function:
var x = 6.5
x.round(.towardZero)
// x == 6.0

// Equivalent to the C 'ceil' function:
var y = 6.5
y.round(.up)
// y == 7.0

// Equivalent to the C 'floor' function:
var z = 6.5
z.round(.down)
// z == 6.0

For more information about the available rounding rules, see the FloatingPointRoundingRule enumeration. To round a value using the default "schoolbook rounding", you can use the shorter round() method instead.

var w1 = 6.5
w1.round()
// w1 == 7.0

rule: The rounding rule to use.

See Also: round(), rounded(_:), FloatingPointRoundingRule

Declaration

mutating func round(_ rule: FloatingPointRoundingRule)

Declared In

FloatingPoint
func rounded(_:)

Returns this value rounded to an integral value using the specified rounding rule.

The following example rounds a value using four different rounding rules:

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

For more information about the available rounding rules, see the FloatingPointRoundingRule enumeration. To round a value using the default "schoolbook rounding", you can use the shorter rounded() method instead.

print(x.rounded())
// Prints "7.0"

rule: The rounding rule to use. Returns: The integral value found by rounding using rule.

See Also: rounded(), round(_:), FloatingPointRoundingRule

Declaration

func rounded(_ rule: FloatingPointRoundingRule) -> Self

Declared In

FloatingPoint
func squareRoot()

Returns the square root of the value, rounded to a representable value.

The following example declares a function that calculates the length of the hypotenuse of a right triangle given its two perpendicular sides.

func hypotenuse(_ a: Double, _ b: Double) -> Double {
    return (a * a + b * b).squareRoot()
}

let (dx, dy) = (3.0, 4.0)
let distance = hypotenuse(dx, dy)
// distance == 5.0

Returns: The square root of the value.

See Also: sqrt(_:), formSquareRoot()

Declaration

func squareRoot() -> Self

Declared In

FloatingPoint
mutating func subtract(_:) Required

Subtracts the given value from this value in place, rounding to a representable value.

This method serves as the basis for the in-place subtraction operator (-=). For example:

var (x, y) = (7.5, 7.5)
x.subtract(2.25)
// x == 5.25
y -= 2.25
// y == 5.25

other: The value to subtract.

See Also: subtracting(_:)

Declaration

mutating func subtract(_ other: Self)

Declared In

FloatingPoint
func subtracting(_:)

Returns the difference of this value and the given value, rounded to a representable value.

This method serves as the basis for the subtraction operator (-). For example:

let x = 7.5
print(x.subtracting(2.25))
// Prints "5.25"
print(x - 2.25)
// Prints "5.25"

The subtracting(_:) method implements the addition operation defined by the IEEE 754 specification.

other: The value to subtract from this value. Returns: The difference of this value and other, rounded to a representable value.

See Also: subtract(_:)

Declaration

func subtracting(_ other: Self) -> Self

Declared In

FloatingPoint
func truncatingRemainder(dividingBy:)

Returns the remainder of this value divided by the given value using truncating division.

Performing truncating division with floating-point values results in a truncated integer quotient and a remainder. For values x and y and their truncated integer quotient q, the remainder r satisfies x == y * q + r.

The following example calculates the truncating remainder of dividing 8.625 by 0.75:

let x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.towardZero)
// q == 11.0
let r = x.truncatingRemainder(dividingBy: 0.75)
// r == 0.375

let x1 = 0.75 * q + r
// x1 == 8.625

If this value and other are both finite numbers, the truncating remainder has the same sign as other and is strictly smaller in magnitude. The truncatingRemainder(dividingBy:) method is always exact.

other: The value to use when dividing this value. Returns: The remainder of this value divided by other using truncating division.

See Also: formTruncatingRemainder(dividingBy:), remainder(dividingBy:)

Declaration

func truncatingRemainder(dividingBy other: Self) -> Self

Declared In

FloatingPoint

Default Implementations

init(signOf:magnitudeOf:)

Declaration

init(signOf: Self, magnitudeOf: Self)
static var radix: Int

The radix, or base of exponentiation, for this floating-point type.

All binary floating-point types have a radix of 2. The magnitude of a floating-point value x of type F can be calculated by using the following formula, where ** is exponentiation:

let magnitude = x.significand * F.radix ** x.exponent

Declaration

static var radix: Int { get }
static var ulpOfOne: Self

The unit in the last place of 1.0.

The positive difference between 1.0 and the next greater representable number. The ulpOfOne constant corresponds to the C macros FLT_EPSILON, DBL_EPSILON, and others with a similar purpose.

Declaration

static var ulpOfOne: Self { get }

Declared In

FloatingPoint
var floatingPointClass: FloatingPointClassification

The classification of this value.

A value's floatingPointClass property describes its "class" as described by the IEEE 754 specification.

Declaration

var floatingPointClass: FloatingPointClassification { get }

Declared In

FloatingPoint
var nextDown: Self

The greatest representable value that compares less than this value.

For any finite value x, x.nextDown is greater than x. For nan or -infinity, x.nextDown is x itself. The following special cases also apply:

  • If x is infinity, then x.nextDown is greatestFiniteMagnitude.
  • If x is leastNonzeroMagnitude, then x.nextDown is 0.0.
  • If x is zero, then x.nextDown is -leastNonzeroMagnitude.
  • If x is -greatestFiniteMagnitude, then x.nextDown is -infinity.

Declaration

var nextDown: Self { get }

Declared In

FloatingPoint
func adding(_:)

Returns the sum of this value and the given value, rounded to a representable value.

This method serves as the basis for the addition operator (+). For example:

let x = 1.5
print(x.adding(2.25))
// Prints "3.75"
print(x + 2.25)
// Prints "3.75"

The adding(_:) method implements the addition operation defined by the IEEE 754 specification.

other: The value to add. Returns: The sum of this value and other, rounded to a representable value.

See Also: add(_:)

Declaration

func adding(_ other: Self) -> Self

Declared In

FloatingPoint
func addingProduct(_:_:)

Returns the result of adding the product of the two given values to this value, computed without intermediate rounding.

This method is equivalent to the C fma function and implements the fusedMultiplyAdd operation defined by the IEEE 754 specification.

Parameters: lhs: One of the values to multiply before adding to this value. rhs: The other value to multiply. Returns: The product of lhs and rhs, added to this value.

Declaration

func addingProduct(_ lhs: Self, _ rhs: Self) -> Self

Declared In

FloatingPoint
func divided(by:)

Returns the quotient of this value and the given value, rounded to a representable value.

This method serves as the basis for the division operator (/). For example:

let x = 7.5
let y = x.divided(by: 2.25)
// y == 16.875
let z = x * 2.25
// z == 16.875

The divided(by:) method implements the division operation defined by the IEEE 754 specification.

other: The value to use when dividing this value. Returns: The quotient of this value and other, rounded to a representable value.

See Also: divide(by:)

Declaration

func divided(by other: Self) -> Self

Declared In

FloatingPoint
func isTotallyOrdered(belowOrEqualTo:)

Declaration

func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool
static func maximum(_:_:)

Returns the greater of the two given values.

This method returns the maximum of two values, preserving order and eliminating NaN when possible. For two values x and y, the result of maximum(x, y) is x if x > y, y if x <= y, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.maximum(10.0, -25.0)
// 10.0
Double.maximum(10.0, .nan)
// 10.0
Double.maximum(.nan, -25.0)
// -25.0
Double.maximum(.nan, .nan)
// nan

The maximum method implements the maxNum operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: The greater of x and y, or whichever is a number if the other is NaN.

Declaration

static func maximum(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func maximumMagnitude(_:_:)

Returns the value with greater magnitude.

This method returns the value with greater magnitude of the two given values, preserving order and eliminating NaN when possible. For two values x and y, the result of maximumMagnitude(x, y) is x if x.magnitude > y.magnitude, y if x.magnitude <= y.magnitude, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.maximumMagnitude(10.0, -25.0)
// -25.0
Double.maximumMagnitude(10.0, .nan)
// 10.0
Double.maximumMagnitude(.nan, -25.0)
// -25.0
Double.maximumMagnitude(.nan, .nan)
// nan

The maximumMagnitude method implements the maxNumMag operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: Whichever of x or y has greater magnitude, or whichever is a number if the other is NaN.

Declaration

static func maximumMagnitude(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func minimum(_:_:)

Returns the lesser of the two given values.

This method returns the minimum of two values, preserving order and eliminating NaN when possible. For two values x and y, the result of minimum(x, y) is x if x <= y, y if y < x, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.minimum(10.0, -25.0)
// -25.0
Double.minimum(10.0, .nan)
// 10.0
Double.minimum(.nan, -25.0)
// -25.0
Double.minimum(.nan, .nan)
// nan

The minimum method implements the minNum operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: The minimum of x and y, or whichever is a number if the other is NaN.

Declaration

static func minimum(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
static func minimumMagnitude(_:_:)

Returns the value with lesser magnitude.

This method returns the value with lesser magnitude of the two given values, preserving order and eliminating NaN when possible. For two values x and y, the result of minimumMagnitude(x, y) is x if x.magnitude <= y.magnitude, y if y.magnitude < x.magnitude, or whichever of x or y is a number if the other is a quiet NaN. If both x and y are NaN, or either x or y is a signaling NaN, the result is NaN.

Double.minimumMagnitude(10.0, -25.0)
// 10.0
Double.minimumMagnitude(10.0, .nan)
// 10.0
Double.minimumMagnitude(.nan, -25.0)
// -25.0
Double.minimumMagnitude(.nan, .nan)
// nan

The minimumMagnitude method implements the minNumMag operation defined by the IEEE 754 specification.

Parameters: x: A floating-point value. y: Another floating-point value. Returns: Whichever of x or y has lesser magnitude, or whichever is a number if the other is NaN.

Declaration

static func minimumMagnitude(_ x: Self, _ y: Self) -> Self

Declared In

FloatingPoint
func multiplied(by:)

Returns the product of this value and the given value, rounded to a representable value.

This method serves as the basis for the multiplication operator (*). For example:

let x = 7.5
print(x.multiplied(by: 2.25))
// Prints "16.875"
print(x * 2.25)
// Prints "16.875"

The multiplied(by:) method implements the multiplication operation defined by the IEEE 754 specification.

other: The value to multiply by this value. Returns: The product of this value and other, rounded to a representable value.

See Also: multiply(by:)

Declaration

func multiplied(by other: Self) -> Self

Declared In

FloatingPoint
func negated()

Returns the additive inverse of this value.

The result is always exact. This method serves as the basis for the negation operator (prefixed -). For example:

let x = 21.5
let y = x.negated()
// y == -21.5

Returns: The additive inverse of this value.

See Also: negate()

Declaration

func negated() -> Self

Declared In

FloatingPoint
func remainder(dividingBy:)

Returns the remainder of this value divided by the given value.

For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.

The following example calculates the remainder of dividing 8.625 by 0.75:

let x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.toNearestOrEven)
// q == 12.0
let r = x.remainder(dividingBy: 0.75)
// r == -0.375

let x1 = 0.75 * q + r
// x1 == 8.625

If this value and other are finite numbers, the remainder is in the closed range -abs(other / 2)...abs(other / 2). The remainder(dividingBy:) method is always exact. This method implements the remainder operation defined by the IEEE 754 specification.

other: The value to use when dividing this value. Returns: The remainder of this value divided by other.

See Also: formRemainder(dividingBy:), truncatingRemainder(dividingBy:)

Declaration

func remainder(dividingBy rhs: Self) -> Self

Declared In

FloatingPoint
mutating func round()

Rounds this value to an integral value using "schoolbook rounding."

The round() method uses the .toNearestOrAwayFromZero rounding rule, where a value halfway between two integral values is rounded to the one with greater magnitude. The following example rounds several values using this default rule:

var x = 5.2
x.round()
// x == 5.0
var y = 5.5
y.round()
// y == 6.0
var z = -5.5
z.round()
// z == -6.0

To specify an alternative rule for rounding, use the round(_:) method instead.

See Also: round(_:), rounded(), FloatingPointRoundingRule

Declaration

mutating func round()

Declared In

FloatingPoint
func rounded()

Returns this value rounded to an integral value using "schoolbook rounding."

The rounded() method uses the .toNearestOrAwayFromZero rounding rule, where a value halfway between two integral values is rounded to the one with greater magnitude. The following example rounds several values using this default rule:

(5.2).rounded()
// 5.0
(5.5).rounded()
// 6.0
(-5.2).rounded()
// -5.0
(-5.5).rounded()
// -6.0

To specify an alternative rule for rounding, use the rounded(_:) method instead.

Returns: The nearest integral value, or, if two integral values are equally close, the integral value with greater magnitude.

See Also: rounded(_:), round(), FloatingPointRoundingRule

Declaration

func rounded() -> Self

Declared In

FloatingPoint
func rounded(_:)

Returns this value rounded to an integral value using the specified rounding rule.

The following example rounds a value using four different rounding rules:

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

For more information about the available rounding rules, see the FloatingPointRoundingRule enumeration. To round a value using the default "schoolbook rounding", you can use the shorter rounded() method instead.

print(x.rounded())
// Prints "7.0"

rule: The rounding rule to use. Returns: The integral value found by rounding using rule.

See Also: rounded(), round(_:), FloatingPointRoundingRule

Declaration

func rounded(_ rule: FloatingPointRoundingRule) -> Self

Declared In

FloatingPoint
func squareRoot()

Returns the square root of the value, rounded to a representable value.

The following example declares a function that calculates the length of the hypotenuse of a right triangle given its two perpendicular sides.

func hypotenuse(_ a: Double, _ b: Double) -> Double {
    return (a * a + b * b).squareRoot()
}

let (dx, dy) = (3.0, 4.0)
let distance = hypotenuse(dx, dy)
// distance == 5.0

Returns: The square root of the value.

See Also: sqrt(_:), formSquareRoot()

Declaration

func squareRoot() -> Self

Declared In

FloatingPoint
func subtracting(_:)

Returns the difference of this value and the given value, rounded to a representable value.

This method serves as the basis for the subtraction operator (-). For example:

let x = 7.5
print(x.subtracting(2.25))
// Prints "5.25"
print(x - 2.25)
// Prints "5.25"

The subtracting(_:) method implements the addition operation defined by the IEEE 754 specification.

other: The value to subtract from this value. Returns: The difference of this value and other, rounded to a representable value.

See Also: subtract(_:)

Declaration

func subtracting(_ other: Self) -> Self

Declared In

FloatingPoint
func truncatingRemainder(dividingBy:)

Returns the remainder of this value divided by the given value using truncating division.

Performing truncating division with floating-point values results in a truncated integer quotient and a remainder. For values x and y and their truncated integer quotient q, the remainder r satisfies x == y * q + r.

The following example calculates the truncating remainder of dividing 8.625 by 0.75:

let x = 8.625
print(x / 0.75)
// Prints "11.5"

let q = (x / 0.75).rounded(.towardZero)
// q == 11.0
let r = x.truncatingRemainder(dividingBy: 0.75)
// r == 0.375

let x1 = 0.75 * q + r
// x1 == 8.625

If this value and other are both finite numbers, the truncating remainder has the same sign as other and is strictly smaller in magnitude. The truncatingRemainder(dividingBy:) method is always exact.

other: The value to use when dividing this value. Returns: The remainder of this value divided by other using truncating division.

See Also: formTruncatingRemainder(dividingBy:), remainder(dividingBy:)

Declaration

func truncatingRemainder(dividingBy other: Self) -> Self

Declared In

FloatingPoint