mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2aa24d236 | ||
|
|
eda432142d | ||
|
|
7bd2909875 | ||
|
|
323542cba1 | ||
|
|
98f3d25fe8 | ||
|
|
f3e1e15312 | ||
|
|
8cbda03867 | ||
|
|
b6839260cb | ||
|
|
1879299216 | ||
|
|
53af148f0f | ||
|
|
2c12891617 | ||
|
|
f25a870cec | ||
|
|
3d637e1302 | ||
|
|
b7e48c538c | ||
|
|
7ff707f6f8 | ||
|
|
de5399615c | ||
|
|
f7842a76db | ||
|
|
5bf2f828ef | ||
|
|
65aac0be46 | ||
|
|
55f33b7769 | ||
|
|
5e978d85a2 |
No files matched your search
@@ -9,6 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Real
|
||||
|
||||
// MARK: - Additive structure
|
||||
extension Complex: AdditiveArithmetic {
|
||||
@_transparent
|
||||
@@ -62,7 +64,7 @@ extension Complex {
|
||||
}
|
||||
|
||||
// MARK: - Multiplicative structure
|
||||
extension Complex: Numeric {
|
||||
extension Complex: AlgebraicField {
|
||||
@_transparent
|
||||
public static func *(z: Complex, w: Complex) -> Complex {
|
||||
return Complex(z.x*w.x - z.y*w.y, z.x*w.y + z.y*w.x)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -208,7 +208,7 @@ extension Complex {
|
||||
|
||||
/// The ∞-norm of the value (`max(abs(real), abs(imaginary))`).
|
||||
///
|
||||
/// If you need the euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
|
||||
/// If you need the Euclidean norm (a.k.a. 2-norm) use the `length` or `lengthSquared`
|
||||
/// properties instead.
|
||||
///
|
||||
/// Edge cases:
|
||||
@@ -344,11 +344,23 @@ extension Complex: Hashable {
|
||||
}
|
||||
|
||||
// MARK: - Conformance to Codable
|
||||
// The synthesized conformance works correction for this protocol, unlike
|
||||
// Hashable and Equatable; all we need to do is specify that we conform.
|
||||
// FloatingPoint does not refine Codable, so this is a conditional conformance.
|
||||
extension Complex: Encodable where RealType: Encodable { }
|
||||
extension Complex: Decodable where RealType: Decodable { }
|
||||
extension Complex: Decodable where RealType: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
var unkeyedContainer = try decoder.unkeyedContainer()
|
||||
let x = try unkeyedContainer.decode(RealType.self)
|
||||
let y = try unkeyedContainer.decode(RealType.self)
|
||||
self.init(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex: Encodable where RealType: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var unkeyedContainer = encoder.unkeyedContainer()
|
||||
try unkeyedContainer.encode(x)
|
||||
try unkeyedContainer.encode(y)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Formatting
|
||||
extension Complex: CustomStringConvertible {
|
||||
@@ -369,7 +381,7 @@ extension Complex: CustomDebugStringConvertible {
|
||||
// MARK: - Operations for working with polar form
|
||||
extension Complex {
|
||||
|
||||
/// The euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
|
||||
/// The Euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imaginary*imaginary)`).
|
||||
///
|
||||
/// This property takes care to avoid spurious over- or underflow in
|
||||
/// this computation. For example:
|
||||
|
||||
@@ -7,7 +7,7 @@ This module provides a `Complex` number type generic over an underlying `RealTyp
|
||||
```
|
||||
This module provides approximate feature parity and memory layout compatibility with C, Fortran, and C++ complex types (although the importer cannot map the types for you, buffers may be reinterpreted to shim API defined in other languages).
|
||||
|
||||
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `Numeric` (hence also `AdditiveArithmetic`).
|
||||
The usual arithmetic operators are provided for Complex numbers, as well as conversion to and from polar coordinates and many useful properties, plus conformances to the obvious usual protocols: `Equatable`, `Hashable`, `Codable` (if the underlying `RealType` is), and `AlgebraicField` (hence also `AdditiveArithmetic` and `Numeric`).
|
||||
|
||||
### Dependencies:
|
||||
- The `Real` module.
|
||||
|
||||
@@ -11,8 +11,22 @@
|
||||
|
||||
#define HEADER_SHIM static inline __attribute__((__always_inline__))
|
||||
|
||||
// MARK: - math functions for float
|
||||
// This header uses most of the libm functions, but we don't want to end up
|
||||
// exporting the libm declarations to modules that include NumericsShims, so
|
||||
// we don't want to actually #include <math.h>.
|
||||
//
|
||||
// For most of the functions, we can get around this by using __builtin_func
|
||||
// instead of func, since the compiler knows about these operations, but for
|
||||
// the non-standard extensions, we need to include our own declarations. This
|
||||
// is a little bit risky, in that we might end up missing an attribute that
|
||||
// gets added and effects calling conventions, etc, but that's expected to be
|
||||
// exceedingly rare.
|
||||
//
|
||||
// Still, we'll eventually want to find a better solution to this problem,
|
||||
// especially if people start using this package on systems that are not
|
||||
// Darwin or Ubuntu.
|
||||
|
||||
// MARK: - math functions for float
|
||||
HEADER_SHIM float libm_cosf(float x) {
|
||||
return __builtin_cosf(x);
|
||||
}
|
||||
@@ -131,9 +145,7 @@ HEADER_SHIM float libm_log10f(float x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM float libm_lgammaf(float x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern float lgammaf_r(float, int *);
|
||||
#endif
|
||||
return lgammaf_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
@@ -253,9 +265,7 @@ HEADER_SHIM double libm_log10(double x) {
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM double libm_lgamma(double x, int *signp) {
|
||||
#if __APPLE__
|
||||
extern double lgamma_r(double, int *);
|
||||
#endif
|
||||
return lgamma_r(x, signp);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//===--- AlgebraicField.swift ---------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type modeling an algebraic [field]. Refines the `Numeric` protocol,
|
||||
/// adding division.
|
||||
///
|
||||
/// A field is a set on which addition, subtraction, multiplication, and
|
||||
/// division are defined, and behave basically like those operations on
|
||||
/// the real numbers. More precisely, a field is a commutative group under
|
||||
/// its addition, the non-zero elements of the field form a commutative
|
||||
/// group under its multiplication, and the distributitve law holds.
|
||||
///
|
||||
/// Some common examples of fields include:
|
||||
///
|
||||
/// - the rational numbers
|
||||
/// - the real numbers
|
||||
/// - the complex numbers
|
||||
/// - the integers modulo a prime
|
||||
///
|
||||
/// The most familiar example of a thing that is *not* a field is the integers.
|
||||
/// This may be surprising, since integers seem to have addition, subtraction,
|
||||
/// multiplication and division. Why don't they form a field?
|
||||
///
|
||||
/// Because integer multiplication does not form a group; it's commutative and
|
||||
/// associative, but integers do not have multiplicative inverses.
|
||||
/// I.e. if a is any integer other than 1 or -1, there is no integer b such
|
||||
/// that a*b = 1. The existence of inverses is requried to form a field.
|
||||
///
|
||||
/// If a type `T` conforms to the `Real` protocol, then `T` and `Complex<T>`
|
||||
/// both conform to `AlgebraicField`.
|
||||
///
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - Real
|
||||
/// - Numeric
|
||||
/// - AdditiveArithmetic
|
||||
///
|
||||
/// [field]: https://en.wikipedia.org/wiki/Field_(mathematics)
|
||||
public protocol AlgebraicField: Numeric {
|
||||
|
||||
static func /=(a: inout Self, b: Self)
|
||||
|
||||
static func /(a: Self, b: Self) -> Self
|
||||
|
||||
/// The (approximate) reciprocal (multiplicative inverse) of this number,
|
||||
/// if it is representable.
|
||||
///
|
||||
/// If reciprocal is non-nil, you can replace division by self with
|
||||
/// multiplication by reciprocal and either get exact the same result
|
||||
/// (for finite fields) or approximately the same result up to a typical
|
||||
/// rounding error (for floating-point formats).
|
||||
///
|
||||
/// If self is zero, or if a reciprocal would overflow or underflow such
|
||||
/// that it cannot be accurately represented, the result is nil. Note that
|
||||
/// `.zero.reciprocal`, somewhat surprisingly, is *not* nil for `Real` or
|
||||
/// `Complex` types, because these types have an `.infinity` value that
|
||||
/// acts as the reciprocal of `.zero`.
|
||||
var reciprocal: Self? { get }
|
||||
}
|
||||
|
||||
extension AlgebraicField {
|
||||
@_transparent
|
||||
public static func /(a: Self, b: Self) -> Self {
|
||||
var result = a
|
||||
result /= b
|
||||
return result
|
||||
}
|
||||
|
||||
/// Implementations should be *conservative* with the reciprocal property;
|
||||
/// it is OK to return `nil` even in cases where a reciprocal could be
|
||||
/// represented. For this reason, a default implementation that simply
|
||||
/// always returns `nil` is correct, but conforming types should provide
|
||||
/// a better implementation if possible.
|
||||
public var reciprocal: Self? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//===--- Double+Real.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NumericsShims
|
||||
|
||||
extension Double: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Double) -> Double {
|
||||
libm_cos(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Double) -> Double {
|
||||
libm_sin(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Double) -> Double {
|
||||
libm_tan(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Double) -> Double {
|
||||
libm_acos(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Double) -> Double {
|
||||
libm_asin(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Double) -> Double {
|
||||
libm_atan(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Double) -> Double {
|
||||
libm_cosh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Double) -> Double {
|
||||
libm_sinh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Double) -> Double {
|
||||
libm_tanh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Double) -> Double {
|
||||
libm_acosh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Double) -> Double {
|
||||
libm_asinh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Double) -> Double {
|
||||
libm_atanh(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Double) -> Double {
|
||||
libm_exp(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Double) -> Double {
|
||||
libm_expm1(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Double) -> Double {
|
||||
libm_log(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Double) -> Double {
|
||||
libm_log1p(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Double) -> Double {
|
||||
libm_erf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Double) -> Double {
|
||||
libm_erfc(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Double) -> Double {
|
||||
libm_exp2(x)
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent
|
||||
public static func exp10(_ x: Double) -> Double {
|
||||
libm_exp10(x)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS) && arch(x86_64)
|
||||
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
|
||||
// overflow for values very close to the overflow boundary of the naive
|
||||
// algorithm. Since this is only for macOS, we can just unconditionally
|
||||
// use Float80, which makes the implementation trivial.
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let x80 = Float80(x)
|
||||
let y80 = Float80(y)
|
||||
return Double(Float80.sqrt(x80*x80 + y80*y80))
|
||||
}
|
||||
#else
|
||||
@_transparent
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
libm_hypot(x, y)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Double) -> Double {
|
||||
libm_tgamma(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Double) -> Double {
|
||||
libm_log2(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Double) -> Double {
|
||||
libm_log10(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Double, _ y: Double) -> Double {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_pow(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Double, _ n: Int) -> Double {
|
||||
// If n is exactly representable as Double, we can just call pow:
|
||||
// Note that all calls on a 32b platform go down this path.
|
||||
if let y = Double(exactly: n) { return libm_pow(x, y) }
|
||||
// Otherwise, n is too large to losslessly represent as Double, so we
|
||||
// just split it into two parts, high and low. This is always exact,
|
||||
// so the only source of error is pow itself and the multiplication.
|
||||
//
|
||||
// mask constant is spelled in this funny way because if we just anded
|
||||
// with the hex value, we'd get a compile error on 32b platforms, even
|
||||
// though this whole branch is dead code on 32b.
|
||||
let mask = Int(truncatingIfNeeded: 0x1f_ffff_ffff_ffff as UInt64)
|
||||
let low = n & mask
|
||||
let high = n - low
|
||||
return libm_pow(x, Double(low)) * libm_pow(x, Double(high))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrt(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Double.
|
||||
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Double, x: Double) -> Double {
|
||||
libm_atan2(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Double) -> Double {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgamma(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//===--- Float+Real.swift -------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NumericsShims
|
||||
|
||||
extension Float: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float) -> Float {
|
||||
libm_cosf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Float) -> Float {
|
||||
libm_sinf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Float) -> Float {
|
||||
libm_tanf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Float) -> Float {
|
||||
libm_acosf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Float) -> Float {
|
||||
libm_asinf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Float) -> Float {
|
||||
libm_atanf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Float) -> Float {
|
||||
libm_coshf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Float) -> Float {
|
||||
libm_sinhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Float) -> Float {
|
||||
libm_tanhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Float) -> Float {
|
||||
libm_acoshf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Float) -> Float {
|
||||
libm_asinhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Float) -> Float {
|
||||
libm_atanhf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Float) -> Float {
|
||||
libm_expf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Float) -> Float {
|
||||
libm_expm1f(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Float) -> Float {
|
||||
libm_logf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Float) -> Float {
|
||||
libm_log1pf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Float) -> Float {
|
||||
libm_erff(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Float) -> Float {
|
||||
libm_erfcf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Float) -> Float {
|
||||
libm_exp2f(x)
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent
|
||||
public static func exp10(_ x: Float) -> Float {
|
||||
libm_exp10f(x)
|
||||
}
|
||||
#endif
|
||||
|
||||
@_transparent
|
||||
public static func hypot(_ x: Float, _ y: Float) -> Float {
|
||||
libm_hypotf(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Float) -> Float {
|
||||
libm_tgammaf(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Float) -> Float {
|
||||
libm_log2f(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Float) -> Float {
|
||||
libm_log10f(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float, _ y: Float) -> Float {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float, _ n: Int) -> Float {
|
||||
// If n is exactly representable as Float, we can just call powf:
|
||||
if let y = Float(exactly: n) {
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
// Otherwise, n is too large to losslessly represent as Float.
|
||||
// The range of "interesting" n is -1488522191 ... 1744361944; outside
|
||||
// of this range, all x != 1 overflow or underflow, so only the parity
|
||||
// of x matters. We don't really care about the specific range at all,
|
||||
// only that the bounds fit exactly into two Floats. Mask the low 24
|
||||
// bits of n, get pow with that exponent (this contains the parity),
|
||||
// then get pow with the rest (this may round, but if it does we've
|
||||
// saturated anyway, so it doesn't matter).
|
||||
let low = n & 0xffffff
|
||||
let high = n - low
|
||||
return libm_powf(x, Float(low)) * libm_powf(x, Float(high))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Float, _ n: Int) -> Float {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtf(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float.
|
||||
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Float, x: Float) -> Float {
|
||||
libm_atan2f(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Float) -> Float {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammaf(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//===--- Float80+Real.swift -----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NumericsShims
|
||||
|
||||
// Restrict extension to platforms for which Float80 exists.
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent
|
||||
public static func cos(_ x: Float80) -> Float80 {
|
||||
libm_cosl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sin(_ x: Float80) -> Float80 {
|
||||
libm_sinl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tan(_ x: Float80) -> Float80 {
|
||||
libm_tanl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acos(_ x: Float80) -> Float80 {
|
||||
libm_acosl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asin(_ x: Float80) -> Float80 {
|
||||
libm_asinl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan(_ x: Float80) -> Float80 {
|
||||
libm_atanl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func cosh(_ x: Float80) -> Float80 {
|
||||
libm_coshl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sinh(_ x: Float80) -> Float80 {
|
||||
libm_sinhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func tanh(_ x: Float80) -> Float80 {
|
||||
libm_tanhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func acosh(_ x: Float80) -> Float80 {
|
||||
libm_acoshl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func asinh(_ x: Float80) -> Float80 {
|
||||
libm_asinhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atanh(_ x: Float80) -> Float80 {
|
||||
libm_atanhl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp(_ x: Float80) -> Float80 {
|
||||
libm_expl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func expMinusOne(_ x: Float80) -> Float80 {
|
||||
libm_expm1l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(_ x: Float80) -> Float80 {
|
||||
libm_logl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log(onePlus x: Float80) -> Float80 {
|
||||
libm_log1pl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erf(_ x: Float80) -> Float80 {
|
||||
libm_erfl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func erfc(_ x: Float80) -> Float80 {
|
||||
libm_erfcl(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func exp2(_ x: Float80) -> Float80 {
|
||||
libm_exp2l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func hypot(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
libm_hypotl(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func gamma(_ x: Float80) -> Float80 {
|
||||
libm_tgammal(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log2(_ x: Float80) -> Float80 {
|
||||
libm_log2l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func log10(_ x: Float80) -> Float80 {
|
||||
libm_log10l(x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powl(x, y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
// Every Int value is exactly representable as Float80, so we don't need
|
||||
// to do anything fancy--unlike Float and Double, we can just call the
|
||||
// libm pow function.
|
||||
libm_powl(x, Float80(n))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Float80, _ n: Int) -> Float80 {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtl(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float80.
|
||||
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func atan2(y: Float80, x: Float80) -> Float80 {
|
||||
libm_atan2l(y, x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func logGamma(_ x: Float80) -> Float80 {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammal(x, &dontCare)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -6,7 +6,7 @@ The `Real` module provides that API as a separate module so that you can use it
|
||||
|
||||
## Protocols and Methods
|
||||
|
||||
The module defines three protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
|
||||
The module defines four protocols. The most general is `ElementaryFunctions`, which makes the following functions available:
|
||||
- Exponential functions: `exp`, `expMinusOne`
|
||||
- Logarithmic functions: `log`, `log(onePlus:)`
|
||||
- Trigonometric functions: `cos`, `sin`, `tan`
|
||||
@@ -28,6 +28,9 @@ The `RealFunctions` protocol refines `ElementaryFunctions`, and adds operations
|
||||
The protocol that you will use most often is `Real`, which describes a floating-point type equipped with the full set of basic math functions.
|
||||
This is a great protocol to use in writing generic code, because it has all the basics that you need to implement most numeric functions.
|
||||
|
||||
The fourth protocol is `AlgebraicField`, which `Real` also refines. This protocol is a very small refinement of `Numeric`, adding the `/` and `/=` operators and a `reciprocal` property.
|
||||
The primary use of this protocol is for writing code that is generic over real and complex types.
|
||||
|
||||
## Using Real
|
||||
|
||||
First, either import `Real` directly or import the `Numerics` umbrella module.
|
||||
@@ -70,3 +73,4 @@ Not having this protocol is a significant missing feature for numerical computin
|
||||
[ErrorFunction]: https://en.wikipedia.org/wiki/Error_function
|
||||
[GammaFunction]: https://en.wikipedia.org/wiki/Gamma_function
|
||||
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
|
||||
[Sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function
|
||||
+11
-1
@@ -26,7 +26,8 @@
|
||||
/// -
|
||||
/// - `ElementaryFunctions`
|
||||
/// - `RealFunctions`
|
||||
public protocol Real: FloatingPoint, RealFunctions {
|
||||
/// - `AlgebraicField`
|
||||
public protocol Real: FloatingPoint, RealFunctions, AlgebraicField {
|
||||
}
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
@@ -79,4 +80,13 @@ extension Real {
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
return x.squareRoot()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var reciprocal: Self? {
|
||||
let recip = 1/self
|
||||
if recip.isNormal || isZero || !isFinite {
|
||||
return recip
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
//===--- ScalarConformances.swift -----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// In theory we might be able to get away with using @_silgen_name for these
|
||||
// instead of NumericShims and remove a level of (source-only) indirection.
|
||||
// However, at present if we do that we get a compiler crash when this module
|
||||
// and the Swift platform module are both imported (<rdar://problem/53821031>).
|
||||
import NumericsShims
|
||||
|
||||
// MARK: Float + Real
|
||||
extension Float: Real {
|
||||
@_transparent public static func cos(_ x: Float) -> Float { return libm_cosf(x) }
|
||||
@_transparent public static func sin(_ x: Float) -> Float { return libm_sinf(x) }
|
||||
@_transparent public static func tan(_ x: Float) -> Float { return libm_tanf(x) }
|
||||
@_transparent public static func acos(_ x: Float) -> Float { return libm_acosf(x) }
|
||||
@_transparent public static func asin(_ x: Float) -> Float { return libm_asinf(x) }
|
||||
@_transparent public static func atan(_ x: Float) -> Float { return libm_atanf(x) }
|
||||
@_transparent public static func cosh(_ x: Float) -> Float { return libm_coshf(x) }
|
||||
@_transparent public static func sinh(_ x: Float) -> Float { return libm_sinhf(x) }
|
||||
@_transparent public static func tanh(_ x: Float) -> Float { return libm_tanhf(x) }
|
||||
@_transparent public static func acosh(_ x: Float) -> Float { return libm_acoshf(x) }
|
||||
@_transparent public static func asinh(_ x: Float) -> Float { return libm_asinhf(x) }
|
||||
@_transparent public static func atanh(_ x: Float) -> Float { return libm_atanhf(x) }
|
||||
@_transparent public static func exp(_ x: Float) -> Float { return libm_expf(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float) -> Float { return libm_expm1f(x) }
|
||||
@_transparent public static func log(_ x: Float) -> Float { return libm_logf(x) }
|
||||
@_transparent public static func log(onePlus x: Float) -> Float { return libm_log1pf(x) }
|
||||
@_transparent public static func erf(_ x: Float) -> Float { return libm_erff(x) }
|
||||
@_transparent public static func erfc(_ x: Float) -> Float { return libm_erfcf(x) }
|
||||
@_transparent public static func exp2(_ x: Float) -> Float { return libm_exp2f(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Float) -> Float { return libm_exp10f(x) }
|
||||
#endif
|
||||
@_transparent public static func hypot(_ x: Float, _ y: Float) -> Float { return libm_hypotf(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float) -> Float { return libm_tgammaf(x) }
|
||||
@_transparent public static func log2(_ x: Float) -> Float { return libm_log2f(x) }
|
||||
@_transparent public static func log10(_ x: Float) -> Float { return libm_log10f(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ y: Float) -> Float {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powf(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float, _ n: Int) -> Float {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powf(x, Float(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float, _ n: Int) -> Float {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtf(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float.
|
||||
return Float(signOf: x, magnitudeOf: libm_powf(x.magnitude, 1/Float(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float, x: Float) -> Float {
|
||||
return libm_atan2f(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float) -> Float {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammaf(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Double + Real
|
||||
extension Double: Real {
|
||||
@_transparent public static func cos(_ x: Double) -> Double { return libm_cos(x) }
|
||||
@_transparent public static func sin(_ x: Double) -> Double { return libm_sin(x) }
|
||||
@_transparent public static func tan(_ x: Double) -> Double { return libm_tan(x) }
|
||||
@_transparent public static func acos(_ x: Double) -> Double { return libm_acos(x) }
|
||||
@_transparent public static func asin(_ x: Double) -> Double { return libm_asin(x) }
|
||||
@_transparent public static func atan(_ x: Double) -> Double { return libm_atan(x) }
|
||||
@_transparent public static func cosh(_ x: Double) -> Double { return libm_cosh(x) }
|
||||
@_transparent public static func sinh(_ x: Double) -> Double { return libm_sinh(x) }
|
||||
@_transparent public static func tanh(_ x: Double) -> Double { return libm_tanh(x) }
|
||||
@_transparent public static func acosh(_ x: Double) -> Double { return libm_acosh(x) }
|
||||
@_transparent public static func asinh(_ x: Double) -> Double { return libm_asinh(x) }
|
||||
@_transparent public static func atanh(_ x: Double) -> Double { return libm_atanh(x) }
|
||||
@_transparent public static func exp(_ x: Double) -> Double { return libm_exp(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Double) -> Double { return libm_expm1(x) }
|
||||
@_transparent public static func log(_ x: Double) -> Double { return libm_log(x) }
|
||||
@_transparent public static func log(onePlus x: Double) -> Double { return libm_log1p(x) }
|
||||
@_transparent public static func erf(_ x: Double) -> Double { return libm_erf(x) }
|
||||
@_transparent public static func erfc(_ x: Double) -> Double { return libm_erfc(x) }
|
||||
@_transparent public static func exp2(_ x: Double) -> Double { return libm_exp2(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_transparent public static func exp10(_ x: Double) -> Double { return libm_exp10(x) }
|
||||
#endif
|
||||
#if os(macOS) && arch(x86_64)
|
||||
// Workaround for macOS bug (<rdar://problem/56844150>) where hypot can
|
||||
// overflow for values very close to the overflow boundary of the naive
|
||||
// algorithm. Since this is only for macOS, we can just unconditionally
|
||||
// use Float80, which makes the implementation trivial.
|
||||
public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
if x.isInfinite || y.isInfinite { return .infinity }
|
||||
let x80 = Float80(x)
|
||||
let y80 = Float80(y)
|
||||
return Double(Float80.sqrt(x80*x80 + y80*y80))
|
||||
}
|
||||
#else
|
||||
@_transparent public static func hypot(_ x: Double, _ y: Double) -> Double {
|
||||
return libm_hypot(x, y)
|
||||
}
|
||||
#endif
|
||||
@_transparent public static func gamma(_ x: Double) -> Double { return libm_tgamma(x) }
|
||||
@_transparent public static func log2(_ x: Double) -> Double { return libm_log2(x) }
|
||||
@_transparent public static func log10(_ x: Double) -> Double { return libm_log10(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ y: Double) -> Double {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_pow(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Double, _ n: Int) -> Double {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Double. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_pow(x, Double(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Double, _ n: Int) -> Double {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrt(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Double.
|
||||
return Double(signOf: x, magnitudeOf: libm_pow(x.magnitude, 1/Double(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Double, x: Double) -> Double {
|
||||
return libm_atan2(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Double) -> Double {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgamma(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: Float80 + Real
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent public static func cos(_ x: Float80) -> Float80 { return libm_cosl(x) }
|
||||
@_transparent public static func sin(_ x: Float80) -> Float80 { return libm_sinl(x) }
|
||||
@_transparent public static func tan(_ x: Float80) -> Float80 { return libm_tanl(x) }
|
||||
@_transparent public static func acos(_ x: Float80) -> Float80 { return libm_acosl(x) }
|
||||
@_transparent public static func asin(_ x: Float80) -> Float80 { return libm_asinl(x) }
|
||||
@_transparent public static func atan(_ x: Float80) -> Float80 { return libm_atanl(x) }
|
||||
@_transparent public static func cosh(_ x: Float80) -> Float80 { return libm_coshl(x) }
|
||||
@_transparent public static func sinh(_ x: Float80) -> Float80 { return libm_sinhl(x) }
|
||||
@_transparent public static func tanh(_ x: Float80) -> Float80 { return libm_tanhl(x) }
|
||||
@_transparent public static func acosh(_ x: Float80) -> Float80 { return libm_acoshl(x) }
|
||||
@_transparent public static func asinh(_ x: Float80) -> Float80 { return libm_asinhl(x) }
|
||||
@_transparent public static func atanh(_ x: Float80) -> Float80 { return libm_atanhl(x) }
|
||||
@_transparent public static func exp(_ x: Float80) -> Float80 { return libm_expl(x) }
|
||||
@_transparent public static func expMinusOne(_ x: Float80) -> Float80 { return libm_expm1l(x) }
|
||||
@_transparent public static func log(_ x: Float80) -> Float80 { return libm_logl(x) }
|
||||
@_transparent public static func log(onePlus x: Float80) -> Float80 { return libm_log1pl(x) }
|
||||
@_transparent public static func erf(_ x: Float80) -> Float80 { return libm_erfl(x) }
|
||||
@_transparent public static func erfc(_ x: Float80) -> Float80 { return libm_erfcl(x) }
|
||||
@_transparent public static func exp2(_ x: Float80) -> Float80 { return libm_exp2l(x) }
|
||||
@_transparent public static func hypot(_ x: Float80, _ y: Float80) -> Float80 { return libm_hypotl(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float80) -> Float80 { return libm_tgammal(x) }
|
||||
@_transparent public static func log2(_ x: Float80) -> Float80 { return libm_log2l(x) }
|
||||
@_transparent public static func log10(_ x: Float80) -> Float80 { return libm_log10l(x) }
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
guard x >= 0 else { return .nan }
|
||||
return libm_powl(x, y)
|
||||
}
|
||||
|
||||
@_transparent public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Float80. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now; however, it gets the sign wrong if
|
||||
// it rounds an odd number to an even number, so we should fix it soon.
|
||||
return libm_powl(x, Float80(n))
|
||||
}
|
||||
|
||||
@_transparent public static func root(_ x: Float80, _ n: Int) -> Float80 {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// Workaround the issue mentioned below for the specific case of n = 3
|
||||
// where we can fallback on cbrt.
|
||||
if n == 3 { return libm_cbrtl(x) }
|
||||
// TODO: this implementation is not quite correct, because either n or
|
||||
// 1/n may be not be representable as Float80.
|
||||
return Float80(signOf: x, magnitudeOf: libm_powl(x.magnitude, 1/Float80(n)))
|
||||
}
|
||||
|
||||
@_transparent public static func atan2(y: Float80, x: Float80) -> Float80 {
|
||||
return libm_atan2l(y, x)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float80) -> Float80 {
|
||||
var dontCare: Int32 = 0
|
||||
return libm_lgammal(x, &dontCare)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
@@ -102,4 +102,31 @@ final class PropertyTests: XCTestCase {
|
||||
testEquatableHashable(Float80.self)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testCodable<T: Codable & Real>(_ type: T.Type) throws {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.nonConformingFloatEncodingStrategy = .convertToString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
|
||||
for expected: Complex<T> in [.zero, .one, .i, .infinity] {
|
||||
let data = try encoder.encode(expected)
|
||||
// print("*** \(String(decoding: data, as: Unicode.UTF8.self)) ***")
|
||||
let actual = try decoder.decode(Complex<T>.self, from: data)
|
||||
XCTAssertEqual(actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testCodable() throws {
|
||||
try testCodable(Float32.self)
|
||||
try testCodable(Float64.self)
|
||||
// Float80 doesn't conform to Codable.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//===--- IntegerExponentTests.swift ---------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Real
|
||||
|
||||
internal extension Real where Self: BinaryFloatingPoint {
|
||||
static func testIntegerExponentCommon() {
|
||||
// If x is -1, then the result is ±1 with sign chosen by parity of n.
|
||||
// Simply converting n to Real will flip parity when n is large, so
|
||||
// first check that we get those cases right.
|
||||
XCTAssertEqual(Self.pow(-1, 0), 1)
|
||||
XCTAssertEqual(Self.pow(-1, 1), -1)
|
||||
XCTAssertEqual(Self.pow(-1, -1), -1)
|
||||
XCTAssertEqual(Self.pow(-1, 2), 1)
|
||||
XCTAssertEqual(Self.pow(-1, -2), 1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.max - 1), 1)
|
||||
XCTAssertEqual(Self.pow(-1, -Int.max + 1), 1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
|
||||
XCTAssertEqual(Self.pow(-1, Int.min), 1)
|
||||
}
|
||||
}
|
||||
|
||||
extension Float {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
let u = Float(1).nextUp
|
||||
let d = Float(1).nextDown
|
||||
// Smallest exponents not exactly representable as Float.
|
||||
assertClose(-7.3890560989306677280287919329569359, Float.pow(-u, 0x1000001))
|
||||
assertClose(-0.3678794082804575860056608283059288, Float.pow(-d, 0x1000001))
|
||||
// Exponents close to overflow boundary.
|
||||
assertClose(-3.4028231352500001570898203463449749e38, Float.pow(-u, 744261161))
|
||||
assertClose( 3.4028235408981285772043562848249166e38, Float.pow(-u, 744261162))
|
||||
assertClose(-3.4028239465463053543440887892352174e38, Float.pow(-u, 744261163))
|
||||
assertClose( 3.4028233551634475284795244782720072e38, Float.pow(-d, -1488522190))
|
||||
assertClose(-3.4028235579875369356575053576685267e38, Float.pow(-d, -1488522191))
|
||||
assertClose( 3.4028237608116384320940078199368685e38, Float.pow(-d, -1488522192))
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 7.0064936491761438872280296737844625e-46, Float.pow(-u, -872181048))
|
||||
assertClose(-7.0064928139371132951305928725186420e-46, Float.pow(-u, -872181049))
|
||||
assertClose( 7.0064919786981822712727285793333389e-46, Float.pow(-u, -872181050))
|
||||
assertClose(-7.0064924138100205091278464932003585e-46, Float.pow(-d, 1744361943))
|
||||
assertClose( 7.0064919961905290625123586120258840e-46, Float.pow(-d, 1744361944))
|
||||
assertClose(-7.0064915785710625079583096856510544e-46, Float.pow(-d, 1744361945))
|
||||
// max/min exponents, these always saturate, but this will reveal
|
||||
// errors in some implementations that one could try.
|
||||
assertClose( .infinity, Self.pow(-u, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-d, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-u, -Int.max + 1))
|
||||
assertClose( .infinity, Self.pow(-d, -Int.max + 1))
|
||||
assertClose(-.infinity, Self.pow(-u, Int.max))
|
||||
assertClose(-0.0, Self.pow(-d, Int.max))
|
||||
assertClose(-0.0, Self.pow(-u, -Int.max))
|
||||
assertClose(-.infinity, Self.pow(-d, -Int.max))
|
||||
assertClose( 0.0, Self.pow(-u, Int.min))
|
||||
assertClose( .infinity, Self.pow(-d, Int.min))
|
||||
}
|
||||
}
|
||||
|
||||
extension Double {
|
||||
static func testIntegerExponent() {
|
||||
testIntegerExponentCommon()
|
||||
// Following tests only make sense (and are only necessary) on 64b platforms.
|
||||
#if arch(arm64) || arch(x86_64)
|
||||
let u: Double = 1.nextUp
|
||||
let d: Double = 1.nextDown
|
||||
// Smallest exponent not exactly representable as Double.
|
||||
assertClose(-7.3890560989306502272304274605750685, Double.pow(-u, 0x20000000000001))
|
||||
assertClose(-0.1353352832366126918939994949724833, Double.pow(-u, -0x20000000000001))
|
||||
assertClose(-0.3678794411714422603312898889458068, Double.pow(-d, 0x20000000000001))
|
||||
assertClose(-2.7182818284590456880451484776630468, Double.pow(-d, -0x20000000000001))
|
||||
// Exponents close to overflow boundary.
|
||||
assertClose( 1.7976931348623151738531864721534215e308, Double.pow(-u, 3196577161300664268))
|
||||
assertClose(-1.7976931348623155730212483790972209e308, Double.pow(-u, 3196577161300664269))
|
||||
assertClose( 1.7976931348623159721893102860411089e308, Double.pow(-u, 3196577161300664270))
|
||||
assertClose( 1.7976931348623157075547244136070910e308, Double.pow(-d, -6393154322601327474))
|
||||
assertClose(-1.7976931348623159071387553670790721e308, Double.pow(-d, -6393154322601327475))
|
||||
assertClose( 1.7976931348623161067227863205510754e308, Double.pow(-d, -6393154322601327476))
|
||||
// Exponents close to underflow boundary.
|
||||
assertClose( 2.4703282292062334560337346683707907e-324, Double.pow(-u, -3355781687888880946))
|
||||
assertClose(-2.4703282292062329075106789791206172e-324, Double.pow(-u, -3355781687888880947))
|
||||
assertClose( 2.4703282292062323589876232898705654e-324, Double.pow(-u, -3355781687888880948))
|
||||
assertClose(-2.4703282292062332640976590913373022e-324, Double.pow(-d, 6711563375777760775))
|
||||
assertClose( 2.4703282292062329898361312467121758e-324, Double.pow(-d, 6711563375777760776))
|
||||
assertClose(-2.4703282292062327155746034020870799e-324, Double.pow(-d, 6711563375777760777))
|
||||
// max/min exponents, these always saturate, but this will reveal
|
||||
// errors in some implementations that one could try.
|
||||
assertClose( .infinity, Self.pow(-u, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-d, Int.max - 1))
|
||||
assertClose( 0.0, Self.pow(-u, -Int.max + 1))
|
||||
assertClose( .infinity, Self.pow(-d, -Int.max + 1))
|
||||
assertClose(-.infinity, Self.pow(-u, Int.max))
|
||||
assertClose(-0.0, Self.pow(-d, Int.max))
|
||||
assertClose(-0.0, Self.pow(-u, -Int.max))
|
||||
assertClose(-.infinity, Self.pow(-d, -Int.max))
|
||||
assertClose( 0.0, Self.pow(-u, Int.min))
|
||||
assertClose( .infinity, Self.pow(-d, Int.min))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
final class IntegerExponentTests: XCTestCase {
|
||||
func testFloat() {
|
||||
Float.testIntegerExponent()
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
Double.testIntegerExponent()
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.testIntegerExponentCommon()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//===--- RealTestSupport.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Real
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
typealias TestLiteralType = Float80
|
||||
#else
|
||||
typealias TestLiteralType = Double
|
||||
#endif
|
||||
|
||||
@discardableResult
|
||||
func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) -> T where T: BinaryFloatingPoint {
|
||||
// Shortcut relative-error check if we got the sign wrong; it's OK to
|
||||
// underflow to zero, but we do not want to allow going right through
|
||||
// zero and getting the sign wrong.
|
||||
guard observed.sign == expected.sign else {
|
||||
print("Sign was wrong: expected \(expected) but saw \(observed).")
|
||||
XCTFail(file: file, line: line)
|
||||
return .infinity
|
||||
}
|
||||
if observed.isNaN && expected.isNaN { return 0 }
|
||||
// If T(expected) is zero or infinite, and matches observed, the error
|
||||
// is zero.
|
||||
let expectedT = T(expected)
|
||||
if observed.isZero && expectedT.isZero { return 0 }
|
||||
if observed.isInfinite && expectedT.isInfinite { return 0 }
|
||||
// Special-case where only one of expectedT or observed is infinity.
|
||||
// Artificially knock everything down a binade, treat actual infinity as
|
||||
// the base of the next binade up.
|
||||
func topBinade(signOf x: T) -> T {
|
||||
T(signOf: x, magnitudeOf: T.greatestFiniteMagnitude.binade)
|
||||
}
|
||||
if observed.isInfinite {
|
||||
return assertClose(
|
||||
expected/2, topBinade(signOf: observed),
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
if expectedT.isInfinite {
|
||||
return assertClose(
|
||||
TestLiteralType(topBinade(signOf: expectedT)), observed/2,
|
||||
allowedError: allowedError, file: file, line: line
|
||||
)
|
||||
}
|
||||
// Compute error in ulp, compare to tolerance.
|
||||
let absoluteError = (TestLiteralType(observed) - expected).magnitude
|
||||
let scale = max(expectedT.magnitude, T.leastNormalMagnitude).ulp
|
||||
let ulps = T(absoluteError/TestLiteralType(scale))
|
||||
if ulps > allowedError {
|
||||
print("ULP error was unacceptably large: expected \(expected) but saw \(observed) (\(ulps)-ulp error).")
|
||||
XCTFail(file: file, line: line)
|
||||
}
|
||||
return ulps
|
||||
}
|
||||
|
||||
func assertClose<T>(
|
||||
_ expected: TestLiteralType,
|
||||
_ observed: T,
|
||||
allowedError: T = 16,
|
||||
worstError: inout T,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) where T: BinaryFloatingPoint {
|
||||
worstError = max(worstError, assertClose(
|
||||
expected, observed, allowedError: allowedError, file: file, line: line
|
||||
))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
|
||||
//===--- ElementaryFunctionChecks.swift ------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
@@ -12,98 +12,67 @@
|
||||
import XCTest
|
||||
import Real
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
typealias TestLiteralType = Float80
|
||||
#else
|
||||
typealias TestLiteralType = Double
|
||||
#endif
|
||||
|
||||
func sanityCheck<T>(_ expected: TestLiteralType, _ actual: T,
|
||||
ulps allowed: T = 16,
|
||||
file: StaticString = #file, line: UInt = #line)
|
||||
where T: BinaryFloatingPoint {
|
||||
// Default tolerance is 16 ulps; It's OK to relax this as needed for new
|
||||
// platforms, as these tests are *not* intended to validate the math
|
||||
// library--they are only intended to check that the Swift bindings are
|
||||
// calling the right functions in the math library. It's important, however
|
||||
// not to relax the tolerance beyond a few hundred ulps, because these tests
|
||||
// need to detect errors where the *wrong function* is being called; e.g.
|
||||
// we need to flag an implentation that inadvertently called the C hypotf
|
||||
// function instead of hypot. This is especially important because the C
|
||||
// shims that we're calling through will allow silent type conversions.
|
||||
if actual == T(expected) || actual.isNaN && expected.isNaN {
|
||||
return
|
||||
}
|
||||
// Compute error in ulp, compare to tolerance.
|
||||
let absoluteError = T(abs(TestLiteralType(actual) - expected))
|
||||
let ulpError = absoluteError / T(expected).ulp
|
||||
XCTAssert(ulpError <= allowed, "\(actual) != \(expected) as \(T.self)" +
|
||||
"\n \(ulpError)-ulp error exceeds \(allowed)-ulp tolerance.",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
internal extension ElementaryFunctions where Self: BinaryFloatingPoint {
|
||||
static func elementaryFunctionTests() {
|
||||
sanityCheck(1.1863995522992575361931268186727044683, Self.acos(0.375))
|
||||
sanityCheck(0.3843967744956390830381948729670469737, Self.asin(0.375))
|
||||
sanityCheck(0.3587706702705722203959200639264604997, Self.atan(0.375))
|
||||
sanityCheck(0.9305076219123142911494767922295555080, Self.cos(0.375))
|
||||
sanityCheck(0.3662725290860475613729093517162641571, Self.sin(0.375))
|
||||
sanityCheck(0.3936265759256327582294137871012180981, Self.tan(0.375))
|
||||
sanityCheck(0.4949329230945269058895630995767185785, Self.acosh(1.125))
|
||||
sanityCheck(0.9670596312833237113713762009167286709, Self.asinh(1.125))
|
||||
sanityCheck(0.7331685343967135223291211023213964500, Self.atanh(0.625))
|
||||
sanityCheck(1.0711403467045867672994980155670160493, Self.cosh(0.375))
|
||||
sanityCheck(0.3838510679136145687542956764205024589, Self.sinh(0.375))
|
||||
sanityCheck(0.3583573983507859463193602315531580424, Self.tanh(0.375))
|
||||
sanityCheck(1.4549914146182013360537936919875185083, Self.exp(0.375))
|
||||
sanityCheck(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
|
||||
sanityCheck(-0.980829253011726236856451127452003999, Self.log(0.375))
|
||||
sanityCheck(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
|
||||
sanityCheck(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
|
||||
static func elementaryFunctionChecks() {
|
||||
assertClose(1.1863995522992575361931268186727044683, Self.acos(0.375))
|
||||
assertClose(0.3843967744956390830381948729670469737, Self.asin(0.375))
|
||||
assertClose(0.3587706702705722203959200639264604997, Self.atan(0.375))
|
||||
assertClose(0.9305076219123142911494767922295555080, Self.cos(0.375))
|
||||
assertClose(0.3662725290860475613729093517162641571, Self.sin(0.375))
|
||||
assertClose(0.3936265759256327582294137871012180981, Self.tan(0.375))
|
||||
assertClose(0.4949329230945269058895630995767185785, Self.acosh(1.125))
|
||||
assertClose(0.9670596312833237113713762009167286709, Self.asinh(1.125))
|
||||
assertClose(0.7331685343967135223291211023213964500, Self.atanh(0.625))
|
||||
assertClose(1.0711403467045867672994980155670160493, Self.cosh(0.375))
|
||||
assertClose(0.3838510679136145687542956764205024589, Self.sinh(0.375))
|
||||
assertClose(0.3583573983507859463193602315531580424, Self.tanh(0.375))
|
||||
assertClose(1.4549914146182013360537936919875185083, Self.exp(0.375))
|
||||
assertClose(0.4549914146182013360537936919875185083, Self.expMinusOne(0.375))
|
||||
assertClose(-0.980829253011726236856451127452003999, Self.log(0.375))
|
||||
assertClose(0.3184537311185346158102472135905995955, Self.log(onePlus: 0.375))
|
||||
assertClose(-0.7211247851537041911608191553900547941, Self.root(-0.375, 3))
|
||||
XCTAssertEqual(-10, Self.root(-1000, 3))
|
||||
sanityCheck(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
|
||||
sanityCheck(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
|
||||
sanityCheck(-0.052734375, Self.pow(-0.375, 3))
|
||||
assertClose(0.6123724356957945245493210186764728479, Self.sqrt(0.375))
|
||||
assertClose(0.54171335479545025876069682133938570, Self.pow(0.375, 0.625))
|
||||
assertClose(-0.052734375, Self.pow(-0.375, 3))
|
||||
}
|
||||
}
|
||||
|
||||
internal extension Real where Self: BinaryFloatingPoint {
|
||||
static func realFunctionTests() {
|
||||
sanityCheck(1.2968395546510096659337541177924511598, Self.exp2(0.375))
|
||||
sanityCheck(2.3713737056616552616517527574788898386, Self.exp10(0.375))
|
||||
sanityCheck(-1.415037499278843818546261056052183491, Self.log2(0.375))
|
||||
sanityCheck(-0.425968732272281148346188780918363771, Self.log10(0.375))
|
||||
sanityCheck(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
|
||||
sanityCheck(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
|
||||
sanityCheck(0.4041169094348222983238250859191217675, Self.erf(0.375))
|
||||
sanityCheck(0.5958830905651777016761749140808782324, Self.erfc(0.375))
|
||||
sanityCheck(2.3704361844166009086464735041766525098, Self.gamma(0.375))
|
||||
static func realFunctionChecks() {
|
||||
assertClose(1.2968395546510096659337541177924511598, Self.exp2(0.375))
|
||||
assertClose(2.3713737056616552616517527574788898386, Self.exp10(0.375))
|
||||
assertClose(-1.415037499278843818546261056052183491, Self.log2(0.375))
|
||||
assertClose(-0.425968732272281148346188780918363771, Self.log10(0.375))
|
||||
assertClose(0.54041950027058415544357836460859991, Self.atan2(y: 0.375, x: 0.625))
|
||||
assertClose(0.72886898685566255885926910969319788, Self.hypot(0.375, 0.625))
|
||||
assertClose(0.4041169094348222983238250859191217675, Self.erf(0.375))
|
||||
assertClose(0.5958830905651777016761749140808782324, Self.erfc(0.375))
|
||||
assertClose(2.3704361844166009086464735041766525098, Self.gamma(0.375))
|
||||
#if !os(Windows)
|
||||
sanityCheck( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
|
||||
assertClose( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
|
||||
XCTAssertEqual(.plus, Self.signGamma(1.375))
|
||||
XCTAssertEqual(.minus, Self.signGamma(-2.375))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
final class ElementaryFunctionChecks: XCTestCase {
|
||||
|
||||
func testFloat() {
|
||||
Float.elementaryFunctionTests()
|
||||
Float.realFunctionTests()
|
||||
Float.elementaryFunctionChecks()
|
||||
Float.realFunctionChecks()
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
Double.elementaryFunctionTests()
|
||||
Double.realFunctionTests()
|
||||
Double.elementaryFunctionChecks()
|
||||
Double.realFunctionChecks()
|
||||
}
|
||||
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.elementaryFunctionTests()
|
||||
Float80.realFunctionTests()
|
||||
Float80.elementaryFunctionChecks()
|
||||
Float80.realFunctionChecks()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Reference in new issue
Block a user