protocol FloatingPoint A floating-point numeric type. Inheritance Hashable, SignedNumeric, Strideable Conforming Types BinaryFloatingPoint Associated Types associatedtype Exponent Floating-point types are used to represent fractional numbers, like 5.5, 100.0, or 3.14159274. Each floating-point type has its own possible range and precision. The floating-point types in the standard library are Float, Double, and Float80 where available. Create new instances of floating-point types using integer or floating-point literals. For example: let temperature = 33.2 let recordHigh = 37.5 The FloatingPoint protocol declares common arithmetic operations, so you can write functions and algorithms that work on any floating-point type. The following example declares a function that calculates the length of the hypotenuse of a right triangle given its two perpendicular sides. Because the hypotenuse(_:_:) function uses a generic parameter constrained to the FloatingPoint protocol, you can call it using any floating-point type. func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { return (a * a + b * b).squareRoot() } let (dx, dy) = (3.0, 4.0) let distance = hypotenuse(dx, dy) // distance == 5.0 Floating-point values are represented as a sign and a magnitude, where the magnitude is calculated using the type's radix and the instance's significand and exponent. This magnitude calculation takes the following form for a floating-point value x of type F, where ** is exponentiation: x.significand * F.radix ** x.exponent Here's an example of the number -8.5 represented as an instance of the Double type, which defines a radix of 2. let y = -8.5 // y.sign == .minus // y.significand == 1.0625 // y.exponent == 3 let magnitude = 1.0625 * Double(2 ** 3) // magnitude == 8.5 Types that conform to the FloatingPoint protocol provide most basic (clause 5) operations of the IEEE 754 specification. The base, precision, and exponent range are not fixed in any way by this protocol, but it enforces the basic requirements of any IEEE 754 floating-point type. Additional Considerations In addition to representing specific numbers, floating-point types also have special values for working with overflow and nonnumeric results of calculation. Infinity Any value whose magnitude is so great that it would round to a value outside the range of representable numbers is rounded to infinity. For a type F, positive and negative infinity are represented as F.infinity and -F.infinity, respectively. Positive infinity compares greater than every finite value and negative infinity, while negative infinity compares less than every finite value and positive infinity. Infinite values with the same sign are equal to each other. let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] print(values.sorted()) // Prints "[-inf, -10.0, 10.0, 25.0, inf]" Operations with infinite values follow real arithmetic as much as possible: Adding or subtracting a finite value, or multiplying or dividing infinity by a nonzero finite value, results in infinity. NaN ("not a number") Floating-point types represent values that are neither finite numbers nor infinity as NaN, an abbreviation for "not a number." Comparing a NaN with any value, including another NaN, results in false. let myNaN = Double.nan print(myNaN > 0) // Prints "false" print(myNaN < 0) // Prints "false" print(myNaN == .nan) // Prints "false" Because testing whether one NaN is equal to another NaN results in false, use the isNaN property to test whether a value is NaN. print(myNaN.isNaN) // Prints "true" NaN propagates through many arithmetic operations. When you are operating on many values, this behavior is valuable because operations on NaN simply forward the value and don't cause runtime errors. The following example shows how NaN values operate in different contexts. Imagine you have a set of temperature data for which you need to report some general statistics: the total number of observations, the number of valid observations, and the average temperature. First, a set of observations in Celsius is parsed from strings to Double values: let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] let tempsCelsius = temperatureData.map { Double($0) ?? .nan } // tempsCelsius == [21.5, 19.25, 27, nan, 28.25, nan, 23.0] Note that some elements in the temperatureData array are not valid numbers. When these invalid strings are parsed by the Double failable initializer, the example uses the nil-coalescing operator (??) to provide NaN as a fallback value. Next, the observations in Celsius are converted to Fahrenheit: let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } // tempsFahrenheit == [70.7, 66.65, 80.6, nan, 82.85, nan, 73.4] The NaN values in the tempsCelsius array are propagated through the conversion and remain NaN in tempsFahrenheit. Because calculating the average of the observations involves combining every value of the tempsFahrenheit array, any NaN values cause the result to also be NaN, as seen in this example: let badAverage = tempsFahrenheit.reduce(0.0, combine: +) / Double(tempsFahrenheit.count) // badAverage.isNaN == true Instead, when you need an operation to have a specific numeric result, filter out any NaN values using the isNaN property. let validTemps = tempsFahrenheit.filter { !$0.isNaN } let average = validTemps.reduce(0.0, combine: +) / Double(validTemps.count) Finally, report the average temperature and observation counts: print("Average: \(average)°F in \(validTemps.count) " + "out of \(tempsFahrenheit.count) observations.") // Prints "Average: 74.84°F in 5 out of 7 observations." Initializers init init(_:) Required Creates a new value, rounded to the closest possible representation. If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern. Parameter value: The integer to convert to a floating-point value. Declaration init(_ value: Int) init init(_:) Required Creates a new value, rounded to the closest possible representation. If two representable values are equally close, the result is the value with more trailing zeros in its significand bit pattern. Parameter value: The integer to convert to a floating-point value. Declaration init<Source>(_ value: Source) where Source: BinaryInteger init 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 exponentiation, 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: 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. Declaration init(sign: FloatingPointSign, exponent: Self.Exponent, significand: Self) init init(signOf:magnitudeOf:) Required 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. Declaration init(signOf: Self, magnitudeOf: Self) init init?(exactly:) Required Creates a new value, if the given integer can be represented exactly. If the given integer cannot be represented exactly, the result is nil. Parameter value: The integer to convert to a floating-point value. Declaration init?<Source>(exactly value: Source) where Source: BinaryInteger Instance Variables var 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: This property implements the logB operation defined by the IEEE 754 specification. Declaration var exponent: Self.Exponent var floatingPointClass Required The classification of this value. A value's floatingPointClass property describes its "class" as described by the IEEE 754 specification. Declaration var floatingPointClass: FloatingPointClassification var isCanonical Required A Boolean value indicating whether the instance's representation is in its canonical form. The IEEE 754 specification defines a canonical, or preferred, encoding of a floating-point value. On platforms that fully support IEEE 754, every Float or Double value is canonical, but non-canonical values can exist on other platforms or for other types. Some examples: Declaration var isCanonical: Bool var isFinite 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 var isInfinite 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 var isNaN 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 var isNormal 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 var isSignalingNaN 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 var isSubnormal 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 var isZero 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 var nextDown Required The greatest representable value that compares less than this value. For any finite value x, x.nextDown is less than x. For nan or -infinity, x.nextDown is x itself. The following special cases also apply: Declaration var nextDown: Self var nextUp 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: Declaration var nextUp: Self var sign 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 Do not 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 var significand 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: 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 var ulp Required The unit in the last place of this value. This is the unit of the least significant digit in this value's significand. 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: See also the ulpOfOne static property. Declaration var ulp: Self Instance Methods func addProduct(_ lhs: Self, _ rhs: Self) Required Adds the product of the two given values to this value in place, computed without intermediate rounding. Declaration mutating func addProduct(_ lhs: Self, _ rhs: Self) func addingProduct(_ lhs: Self, _ rhs: Self) -> Self Required 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. Declaration func addingProduct(_ lhs: Self, _ rhs: Self) -> Self func formRemainder(dividingBy other: Self) 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 formRemainder(dividingBy:) method is always exact. Parameter other: The value to use when dividing this value. Declaration mutating func formRemainder(dividingBy other: Self) func formSquareRoot() Required Replaces this value with its square root, rounded to a representable value. Declaration mutating func formSquareRoot() func formTruncatingRemainder(dividingBy other: Self) 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 this value and is strictly smaller in magnitude than other. The formTruncatingRemainder(dividingBy:) method is always exact. Parameter other: The value to use when dividing this value. Declaration mutating func formTruncatingRemainder(dividingBy other: Self) func isEqual(to other: Self) -> Bool 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. Parameter other: The value to compare with this value. Declaration func isEqual(to other: Self) -> Bool func isLess(than other: Self) -> Bool 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: The isLess(than:) method implements the less-than predicate defined by the IEEE 754 specification. Parameter other: The value to compare with this value. Declaration func isLess(than other: Self) -> Bool func isLessThanOrEqualTo(_ other: Self) -> Bool 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: The isLessThanOrEqualTo(_:) method implements the less-than-or-equal predicate defined by the IEEE 754 specification. Parameter other: The value to compare with this value. Declaration func isLessThanOrEqualTo(_ other: Self) -> Bool func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool Required Returns a Boolean value indicating whether this instance should precede or tie positions with 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 signed zeros and NaNs. The following example uses isTotallyOrdered(belowOrEqualTo:) 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 { !$1.isTotallyOrdered(belowOrEqualTo: $0) } // 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. Parameter other: A floating-point value to compare to this value. Declaration func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool 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 Declaration override mutating func negate() func remainder(dividingBy other: Self) -> Self Required 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. Parameter other: The value to use when dividing this value. Declaration func remainder(dividingBy other: Self) -> Self func round(_ rule: FloatingPointRoundingRule) 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 Parameter rule: The rounding rule to use. Declaration mutating func round(_ rule: FloatingPointRoundingRule) func rounded(_ rule: FloatingPointRoundingRule) -> Self Required 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" Parameter rule: The rounding rule to use. Declaration func rounded(_ rule: FloatingPointRoundingRule) -> Self func squareRoot() -> Self Required 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 Declaration func squareRoot() -> Self func truncatingRemainder(dividingBy other: Self) -> Self Required 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 this value and is strictly smaller in magnitude than other. The truncatingRemainder(dividingBy:) method is always exact. Parameter other: The value to use when dividing this value. Declaration func truncatingRemainder(dividingBy other: Self) -> Self Type Variables var greatestFiniteMagnitude 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 var greatestFiniteMagnitude: Self var infinity 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 var infinity: Self var leastNonzeroMagnitude 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 var leastNonzeroMagnitude: Self var leastNormalMagnitude 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 var leastNormalMagnitude: Self var nan 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" Declaration var nan: Self var pi 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 var pi: Self var radix Required 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 var radix: Int var signalingNaN 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. Declaration var signalingNaN: Self var ulpOfOne Required The unit in the last place of 1.0. The positive difference between 1.0 and the next greater representable number. ulpOfOne corresponds to the value represented by the C macros FLT_EPSILON, DBL_EPSILON, etc, and is sometimes called epsilon or machine epsilon. Swift deliberately avoids using the term "epsilon" because: See also the ulp member property. Declaration var ulpOfOne: Self Type Methods func *(lhs: Self, rhs: Self) -> Self Required Multiplies two values and produces their product, rounding to a representable value. The multiplication operator (*) calculates the product of its two arguments. For example: let x = 7.5 let y = x * 2.25 // y == 16.875 The * operator implements the multiplication operation defined by the IEEE 754 specification. Declaration override static func *(lhs: Self, rhs: Self) -> Self func *=(lhs: inout Self, rhs: Self) Required Multiplies two values and stores the result in the left-hand-side variable, rounding to a representable value. Declaration override static func *=(lhs: inout Self, rhs: Self) func +(lhs: Self, rhs: Self) -> Self Required Adds two values and produces their sum, rounded to a representable value. The addition operator (+) calculates the sum of its two arguments. For example: let x = 1.5 let y = x + 2.25 // y == 3.75 The + operator implements the addition operation defined by the IEEE 754 specification. Declaration override static func +(lhs: Self, rhs: Self) -> Self func +=(lhs: inout Self, rhs: Self) Required Adds two values and stores the result in the left-hand-side variable, rounded to a representable value. Declaration override static func +=(lhs: inout Self, rhs: Self) func -(lhs: Self, rhs: Self) -> Self Required Subtracts one value from another and produces their difference, rounded to a representable value. The subtraction operator (-) calculates the difference of its two arguments. For example: let x = 7.5 let y = x - 2.25 // y == 5.25 The - operator implements the subtraction operation defined by the IEEE 754 specification. Declaration override static func -(lhs: Self, rhs: Self) -> Self func -(operand: Self) -> Self Required Calculates the additive inverse of a value. The unary minus operator (prefix -) calculates the negation of its operand. The result is always exact. let x = 21.5 let y = -x // y == -21.5 Parameter operand: The value to negate. Declaration override prefix static func -(operand: Self) -> Self func -=(lhs: inout Self, rhs: Self) Required Subtracts the second value from the first and stores the difference in the left-hand-side variable, rounding to a representable value. Declaration override static func -=(lhs: inout Self, rhs: Self) func /(lhs: Self, rhs: Self) -> Self Required Returns the quotient of dividing the first value by the second, rounded to a representable value. The division operator (/) calculates the quotient of the division if rhs is nonzero. If rhs is zero, the result of the division is infinity, with the sign of the result matching the sign of lhs. let x = 16.875 let y = x / 2.25 // y == 7.5 let z = x / 0 // z.isInfinite == true The / operator implements the division operation defined by the IEEE 754 specification. Declaration static func /(lhs: Self, rhs: Self) -> Self func /=(lhs: inout Self, rhs: Self) Required Divides the first value by the second and stores the quotient in the left-hand-side variable, rounding to a representable value. Declaration static func /=(lhs: inout Self, rhs: Self) func maximum(_ x: Self, _ y: Self) -> Self Required 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. Declaration static func maximum(_ x: Self, _ y: Self) -> Self func maximumMagnitude(_ x: Self, _ y: Self) -> Self Required 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. Declaration static func maximumMagnitude(_ x: Self, _ y: Self) -> Self func minimum(_ x: Self, _ y: Self) -> Self Required 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. Declaration static func minimum(_ x: Self, _ y: Self) -> Self func minimumMagnitude(_ x: Self, _ y: Self) -> Self Required 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. Declaration static func minimumMagnitude(_ x: Self, _ y: Self) -> Self Default Implementations func -(operand: Self) -> Self Returns the additive inverse of the specified value. The negation operator (prefix -) returns the additive inverse of its argument. let x = 21 let y = -x // y == -21 The resulting value must be representable in the same type as the argument. In particular, negating a signed, fixed-width integer type's minimum results in a value that cannot be represented. let z = -Int8.min // Overflow error Declaration prefix public static func -(operand: Self) -> Self func <(x: Self, y: Self) -> Bool 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. Declaration @inlinable public static func <(x: Self, y: Self) -> Bool func ==(x: Self, y: Self) -> Bool 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. Declaration @inlinable public static func ==(x: Self, y: Self) -> Bool func negate() Replaces this value with its additive inverse. The following example uses the negate() method to negate the value of an integer x: var x = 21 x.negate() // x == -21 The resulting value must be representable within the value's type. In particular, negating a signed, fixed-width integer type's minimum results in a value that cannot be represented. var y = Int8.min y.negate() // Overflow error Declaration public mutating func negate()