mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Initial project setup for swift-numerics
Two modules to begin with: - ElementaryFunctions - Complex Added README.md files describing each module very roughly, and a project README to describe goals and process.
This commit is contained in:
commit
8aab7a90f8
18 files changed
+2205
No files matched your search
@@ -0,0 +1,5 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
/.swiftpm
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
|
||||
## Runtime Library Exception to the Apache 2.0 License: ##
|
||||
|
||||
|
||||
As an exception, if you use this Software to compile your source code and
|
||||
portions of this Software are embedded into the binary product as a result,
|
||||
you may redistribute such product without providing attribution as would
|
||||
otherwise be required by Sections 4(a), 4(b) and 4(d) of the License.
|
||||
@@ -0,0 +1,32 @@
|
||||
// swift-tools-version:5.0
|
||||
//===--- Package.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "Complex", targets: ["Complex"]),
|
||||
.library(name: "ElementaryFunctions", targets: ["ElementaryFunctions"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
targets: [
|
||||
.target(name: "Complex", dependencies: ["ElementaryFunctions"]),
|
||||
.target(name: "ElementaryFunctions", dependencies: ["NumericsShims"]),
|
||||
.target(name: "NumericsShims", dependencies: []),
|
||||
|
||||
.testTarget(name: "ComplexTests", dependencies: ["Complex"]),
|
||||
.testTarget(name: "ElementaryFunctionTests", dependencies: ["ElementaryFunctions"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
# Swift-Numerics
|
||||
|
||||
## Introduction
|
||||
Swift-numerics provides a set of modules that support numerical computing in Swift.
|
||||
These modules fall broadly in two categories:
|
||||
|
||||
- API that is too specialized to go into the standard library, but which is sufficiently
|
||||
general to be centralized in a single common package.
|
||||
- API that is under active development toward possible future inclusion in the
|
||||
standard library.
|
||||
|
||||
There is some overlap between these two categories, and API that begins in the first
|
||||
category may migrate to the second as it matures and new uses are discovered.
|
||||
|
||||
Swift-numerics modules are fine-grained; if a user needs support for Complex numbers,
|
||||
they can import the Complex module without pulling in a module for linear algebra as well.
|
||||
|
||||
Swift-numerics modules have minimal dependencies on other projects. It assumes only
|
||||
the availability of the Swift and C standard libraries, and the runtime support provided
|
||||
by compiler-rt. Future expansion may assume the availability of other standard
|
||||
interfaces such as BLAS and LAPACK, but modules with more specialized
|
||||
dependencies probably belong in a separate package.
|
||||
|
||||
## Process
|
||||
Swift-numerics changes are not expected to go through swift-evolution. For some
|
||||
modules, swift-numerics may act as a staging area for the standard library, but in
|
||||
those cases, the expectation is that swift-evolution review will take place at the point
|
||||
that the module is proposed for inclusion. It's good to keep that process in mind,
|
||||
however, and document *why* you're making the decisions that you are, so that
|
||||
reviewers can refer to those rationales when a module comes up for swift-evolution.
|
||||
|
||||
Swift-numerics uses github issues to track bugs and features, and pull requests for
|
||||
development.
|
||||
|
||||
To propose a new module:
|
||||
1. Raise an issue with the [new module] tag.
|
||||
2. Raise a PR with an implementation sketch.
|
||||
3. Once you have some consensus, ask an admin to create a feature branch against
|
||||
which PRs can be raised.
|
||||
4. When the design has stabilized and is functional enough to be useful, raise a PR
|
||||
to merge the new module to master.
|
||||
|
||||
To propose a new feature for an existing module:
|
||||
1. Raise an issue with the [enhancement] tag.
|
||||
2. Raise a PR with an implementation, and discuss the implementation there.
|
||||
3. Once there is consensus that the new feature is desirable and the design is suitable,
|
||||
it can be merged.
|
||||
|
||||
To fix a bug, or make smaller improvements:
|
||||
1. Raise a PR with your change. Be sure to add test coverage for whatever changes you are making.
|
||||
|
||||
## Modules
|
||||
1. [ElementaryFunctions](Sources/ElementaryFunctions/README.md)
|
||||
2. [Complex](Sources/Complex/README.md)
|
||||
|
||||
## Future expansion
|
||||
1. [Approximate Equality](https://github.com/apple/swift-numerics/issues/3)
|
||||
2. [Large Fixed-Width Integers](https://github.com/apple/swift-numerics/issues/4)
|
||||
3. [Arbitrary-Precision Integers](https://github.com/apple/swift-numerics/issues/5)
|
||||
4. [Shaped Arrays](https://github.com/apple/swift-numerics/issues/6)
|
||||
4. [Decimal Floating-point](https://github.com/apple/swift-numerics/issues/7)
|
||||
5. [Float16](https://github.com/apple/swift-numerics/issues/8)
|
||||
@@ -0,0 +1,136 @@
|
||||
//===--- Arithmetic.swift -------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Additive structure
|
||||
extension Complex: AdditiveArithmetic {
|
||||
@_transparent
|
||||
public static func +(z: Complex, w: Complex) -> Complex {
|
||||
return Complex(z.x + w.x, z.y + w.y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func -(z: Complex, w: Complex) -> Complex {
|
||||
return Complex(z.x - w.x, z.y - w.y)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func +=(z: inout Complex, w: Complex) {
|
||||
z = z + w
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func -=(z: inout Complex, w: Complex) {
|
||||
z = z - w
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Vector space structure
|
||||
//
|
||||
// Policy: deliberately not using the * and / operators for these at the
|
||||
// moment, because then there's an ambiguity in expressions like 2*z; is
|
||||
// that Complex(2) * z or is it RealType(2) * z? This is especially
|
||||
// problematic in type inference: suppose we have:
|
||||
//
|
||||
// let a: RealType = 1
|
||||
// let b = 2*a
|
||||
//
|
||||
// what is the type of b? If we don't have a type context, it's ambiguous.
|
||||
// If we have a Complex type context, then b will be inferred to have type
|
||||
// Complex! Obviously, that doesn't help anyone.
|
||||
//
|
||||
// TODO: figure out if there's some way to avoid these surprising results
|
||||
// and turn these into operators if/when we have it.
|
||||
// (https://github.com/apple/swift-numerics/issues/12)
|
||||
extension Complex {
|
||||
@inline(__always) @usableFromInline
|
||||
internal func multiplied(by a: RealType) -> Complex {
|
||||
Complex(x*a, y*a)
|
||||
}
|
||||
|
||||
@inline(__always) @usableFromInline
|
||||
internal func divided(by a: RealType) -> Complex {
|
||||
Complex(x/a, y/a)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multiplicative structure
|
||||
extension Complex: Numeric {
|
||||
@inlinable
|
||||
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)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /(z: Complex, w: Complex) -> Complex {
|
||||
// Try the naive expression z/w = z*conj(w) / |w|^2; if the result is
|
||||
// normal, then everything was fine, and we can simply return the result.
|
||||
let naive = z * w.conjugate.divided(by: w.unsafeLengthSquared)
|
||||
guard naive.isNormal else { return carefulDivide(z, w) }
|
||||
return naive
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func *=(z: inout Complex, w: Complex) {
|
||||
z = z * w
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /=(z: inout Complex, w: Complex) {
|
||||
z = z / w
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func carefulDivide(_ z: Complex, _ w: Complex) -> Complex {
|
||||
if z.isZero || !w.isFinite { return .zero }
|
||||
let zScale = z.magnitude
|
||||
let wScale = w.magnitude
|
||||
let zNorm = z.divided(by: zScale)
|
||||
let wNorm = w.divided(by: wScale)
|
||||
let r = (zNorm * wNorm.conjugate).divided(by: wNorm.unsafeLengthSquared)
|
||||
let rScale = r.magnitude
|
||||
// At this point, the result is (r * zScale)/wScale computed without
|
||||
// undue overflow or underflow. We know that r is close to unity, so
|
||||
// the question is simply what order in which to do this computation
|
||||
// to avoid spurious overflow or underflow. There are three options
|
||||
// to choose from:
|
||||
//
|
||||
// - r * (zScale / wScale)
|
||||
// - (r * zScale) / wScale
|
||||
// - (r / wScale) * zScale
|
||||
//
|
||||
// The simplest case is when zScale / wScale is normal:
|
||||
if (zScale / wScale).isNormal {
|
||||
return r.multiplied(by: zScale / wScale)
|
||||
}
|
||||
// Otherwise, we need to compute either rNorm * zScale or rNorm / wScale
|
||||
// first. Choose the first if the first scaling behaves well, otherwise
|
||||
// choose the other one.
|
||||
if (rScale * zScale).isNormal {
|
||||
return r.multiplied(by: zScale).divided(by: wScale)
|
||||
}
|
||||
return r.divided(by: wScale).multiplied(by: zScale)
|
||||
}
|
||||
|
||||
/// A normalized complex number with the same phase as this value.
|
||||
///
|
||||
/// If such a value cannot be produced (because the phase of zero and infinity is undefined),
|
||||
/// `nil` is returned.
|
||||
public var normalized: Complex? {
|
||||
if length.isNormal {
|
||||
return self.divided(by: length)
|
||||
}
|
||||
if isZero || !isFinite {
|
||||
return nil
|
||||
}
|
||||
return self.divided(by: magnitude).normalized
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
//===--- Complex.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import ElementaryFunctions
|
||||
|
||||
/// A complex number represented by real and imaginary parts.
|
||||
///
|
||||
/// TODO: introductory text on complex numbers
|
||||
///
|
||||
/// Implementation notes:
|
||||
///
|
||||
/// Unlike C _Complex and C++ std::complex<> types, which attempt to define
|
||||
/// meaningful fine-grained semantics for complex values with one or both
|
||||
/// components infinite or nan, we simply treat all such values as a single
|
||||
/// equivalence class. This simplifies defining multiplication and division
|
||||
/// considerably, with almost no loss in expressive power.
|
||||
@_fixed_layout
|
||||
public struct Complex<RealType> where RealType: Real {
|
||||
/// The real part of this complex value.
|
||||
@usableFromInline
|
||||
internal var x: RealType
|
||||
|
||||
/// The imaginary part of this complex value.
|
||||
@usableFromInline
|
||||
internal var y: RealType
|
||||
|
||||
/// A complex number constructed by specifying the real and imaginary parts.
|
||||
@inlinable
|
||||
public init(_ real: RealType, _ imag: RealType) {
|
||||
x = real
|
||||
y = imag
|
||||
}
|
||||
|
||||
/// The real part of this complex value if it is a finite number, or `nan` if it is not.
|
||||
public var real: RealType {
|
||||
@inlinable
|
||||
get { isFinite ? x : .nan }
|
||||
}
|
||||
|
||||
/// The imaginary part of this complex value if it is a finite number, or `nan` if it is not.
|
||||
public var imag: RealType {
|
||||
@inlinable
|
||||
get { isFinite ? y : .nan }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Additional Initializers
|
||||
extension Complex {
|
||||
/// The complex number with specified real part and zero imaginary part.
|
||||
@inlinable
|
||||
public init(_ real: RealType) {
|
||||
self.init(real, 0)
|
||||
}
|
||||
|
||||
/// The complex number with specified imaginary part and zero real part.
|
||||
@inlinable
|
||||
public init(imag: RealType) {
|
||||
self.init(0, imag)
|
||||
}
|
||||
|
||||
/// The complex number with specified real part and zero imaginary part.
|
||||
@inlinable
|
||||
public init<Other: BinaryInteger>(_ real: Other) {
|
||||
self.init(RealType(real), 0)
|
||||
}
|
||||
|
||||
/// The complex number with specified real part and zero imaginary part,
|
||||
/// if it can be constructed without rounding.
|
||||
@inlinable
|
||||
public init?<Other: BinaryInteger>(exactly real: Other) {
|
||||
guard let real = RealType(exactly: real) else { return nil }
|
||||
self.init(real, 0)
|
||||
}
|
||||
|
||||
public typealias IntegerLiteralType = Int
|
||||
|
||||
@inlinable
|
||||
public init(integerLiteral value: Int) {
|
||||
self.init(RealType(value))
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex where RealType: BinaryFloatingPoint {
|
||||
/// `other` rounded to the nearest representable value of this type.
|
||||
@inlinable
|
||||
public init<Other: BinaryFloatingPoint>(_ other: Complex<Other>) {
|
||||
self.init(RealType(other.x), RealType(other.y))
|
||||
}
|
||||
|
||||
/// `other`, if it can be represented exactly in this type; otherwise `nil`.
|
||||
@inlinable
|
||||
public init?<Other: BinaryFloatingPoint>(exactly other: Complex<Other>) {
|
||||
guard let real = RealType(exactly: other.x),
|
||||
let imag = RealType(exactly: other.y) else { return nil }
|
||||
self.init(real, imag)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conformance to Hashable and Equatable
|
||||
//
|
||||
// The Complex type identifies all non-finite points (waving hands slightly,
|
||||
// we identify all NaNs and infinites as the point at infinity on the Riemann
|
||||
// sphere).
|
||||
extension Complex: Hashable {
|
||||
@inlinable
|
||||
public static func ==(a: Complex, b: Complex) -> Bool {
|
||||
// Identify all numbers with either component non-finite as a single
|
||||
// "point at infinity".
|
||||
guard a.isFinite || b.isFinite else { return true }
|
||||
// For finite numbers, equality is defined componentwise. Cases where
|
||||
// only one of a or b is infinite fall through to here as well, but this
|
||||
// expression correctly returns false for them so we don't need to handle
|
||||
// them explicitly.
|
||||
return a.x == b.x && a.y == b.y
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
// There are two equivalence classes to which we owe special attention:
|
||||
// All zeros should hash to the same value, regardless of sign, and all
|
||||
// non-finite numbers should hash to the same value, regardless of
|
||||
// representation. The correct behavior for zero falls out for free from
|
||||
// the hash behavior of floating-point, but we need to use a
|
||||
// representative member for any non-finite values.
|
||||
if isFinite {
|
||||
hasher.combine(x)
|
||||
hasher.combine(y)
|
||||
} else {
|
||||
hasher.combine(RealType.infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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: Codable where RealType: Codable {
|
||||
}
|
||||
|
||||
// MARK: - Formatting
|
||||
extension Complex: CustomStringConvertible {
|
||||
public var description: String {
|
||||
guard isFinite else {
|
||||
return "inf"
|
||||
}
|
||||
return "(\(x), \(y))"
|
||||
}
|
||||
}
|
||||
|
||||
extension Complex: CustomDebugStringConvertible where RealType: CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
"Complex<\(RealType.self)>(\(x.debugDescription), \(y.debugDescription))"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Basic properties
|
||||
extension Complex {
|
||||
@inlinable
|
||||
public static var zero: Complex {
|
||||
Complex(0, 0)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static var one: Complex {
|
||||
Complex(1, 0)
|
||||
}
|
||||
|
||||
/// The imaginary unit.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - .zero
|
||||
/// - .one
|
||||
/// - .infinity
|
||||
@inlinable
|
||||
public static var i: Complex {
|
||||
Complex(0, 1)
|
||||
}
|
||||
|
||||
/// A value representing the point at infinity.
|
||||
@inlinable
|
||||
public static var infinity: Complex {
|
||||
Complex(.infinity, 0)
|
||||
}
|
||||
|
||||
/// The complex conjugate of this value.
|
||||
@inlinable
|
||||
public var conjugate: Complex {
|
||||
Complex(x, -y)
|
||||
}
|
||||
|
||||
/// True if this value is finite.
|
||||
///
|
||||
/// A complex value is finite if neither component is an infinity or nan.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.isNormal`
|
||||
/// - `.isSubnormal`
|
||||
/// - `.isZero`
|
||||
@inlinable
|
||||
public var isFinite: Bool {
|
||||
x.isFinite && y.isFinite
|
||||
}
|
||||
|
||||
/// True if this value is normal.
|
||||
///
|
||||
/// A complex number is normal if it is finite and *either* the real or imaginary component is normal.
|
||||
/// A floating-point number representing one of the components is normal if its exponent allows a full-
|
||||
/// precision representation.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.isFinite`
|
||||
/// - `.isSubnormal`
|
||||
/// - `.isZero`
|
||||
@inlinable
|
||||
public var isNormal: Bool {
|
||||
isFinite && (x.isNormal || y.isNormal)
|
||||
}
|
||||
|
||||
/// True if this value is subnormal.
|
||||
///
|
||||
/// A complex number is subnormal if it is finite, not normal, and not zero. When the result of a
|
||||
/// computation is subnormal, underflow has occured and the result generally does not have full
|
||||
/// precision.
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.isFinite`
|
||||
/// - `.isNormal`
|
||||
/// - `.isZero`
|
||||
@inlinable
|
||||
public var isSubnormal: Bool {
|
||||
isFinite && !isNormal && !isZero
|
||||
}
|
||||
|
||||
/// True if this value is zero.
|
||||
///
|
||||
/// A complex number is zero if *both* the real and imaginary components are zero.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.isFinite`
|
||||
/// - `.isNormal`
|
||||
/// - `.isSubnormal`
|
||||
@inlinable
|
||||
public var isZero: Bool {
|
||||
x == 0 && y == 0
|
||||
}
|
||||
|
||||
/// The ∞-norm of the value (`max(abs(real), abs(imag))`).
|
||||
///
|
||||
/// If you need the euclidean norm (a.k.a. 2-norm) use the `length` or `unsafeLengthSquared`
|
||||
/// properties instead.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// If a complex value is not finite, `.magnitude` is `infinity`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.length`
|
||||
/// - `.unsafeLengthSquared`
|
||||
@inlinable
|
||||
public var magnitude: RealType {
|
||||
guard isFinite else { return .infinity }
|
||||
return max(abs(x), abs(y))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Operations for working with polar form
|
||||
extension Complex {
|
||||
|
||||
/// The euclidean norm (a.k.a. 2-norm, `sqrt(real*real + imag*imag)`).
|
||||
///
|
||||
/// This property takes care to avoid spurious over- or underflow in this computation. For example:
|
||||
///
|
||||
/// let x: Float = 3.0e+20
|
||||
/// let x: Float = 4.0e+20
|
||||
/// let naive = sqrt(x*x + y*y) // +Inf
|
||||
/// let careful = Complex(x, y).length // 5.0e+20
|
||||
///
|
||||
/// Note that it *is* still possible for this property to overflow, because the length can be as much
|
||||
/// as sqrt(2) times larger than either component, and thus may not be representable in the real type.
|
||||
///
|
||||
/// For most use cases, you can use the cheaper `.magnitude` property (which computes the
|
||||
/// ∞-norm) instead, which always produces a representable result.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// If a complex value is not finite, its `.length` is `infinity`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.magnitude`
|
||||
/// - `.unsafeLengthSquared`
|
||||
/// - `.phase`
|
||||
/// - `.polar`
|
||||
/// - `init(r:θ:)`
|
||||
@inlinable
|
||||
public var length: RealType {
|
||||
let naive = unsafeLengthSquared
|
||||
guard naive.isNormal else { return carefulLength }
|
||||
return .sqrt(naive)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var carefulLength: RealType {
|
||||
guard isFinite else { return .infinity }
|
||||
return .hypot(x, y)
|
||||
}
|
||||
|
||||
/// The squared length `(real*real + imag*imag)`.
|
||||
///
|
||||
/// This property is more efficient to compute than `length`, but is prone to overflow or underflow;
|
||||
/// for finite values that are not well-scaled, `unsafeLengthSquared` is often either zero or
|
||||
/// infinity, even when `length` is a finite number. Use this property only when you are certain that
|
||||
/// this value is well-scaled.
|
||||
///
|
||||
/// For many cases, `.magnitude` can be used instead, which is also cheap to compute and always
|
||||
/// returns a representable value.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.length`
|
||||
/// - `.magnitude`
|
||||
@inlinable
|
||||
public var unsafeLengthSquared: RealType {
|
||||
x*x + y*y
|
||||
}
|
||||
|
||||
/// The phase (angle, or "argument").
|
||||
///
|
||||
/// Returns the angle (measured above the real axis) in radians. If the complex value is zero
|
||||
/// or infinity, the phase is not defined, and `nan` is returned.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// If the complex value is zero or non-finite, phase is `nan`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.length`
|
||||
/// - `.polar`
|
||||
/// - `init(r:θ:)`
|
||||
@inlinable
|
||||
public var phase: RealType {
|
||||
guard isFinite && !isZero else { return .nan }
|
||||
return .atan2(y: y, x: x)
|
||||
}
|
||||
|
||||
/// The length and phase (or polar coordinates) of this value.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// If the complex value is zero or non-finite, phase is `.nan`. If the complex value is non-finite,
|
||||
/// the length is `.infinity`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.length`
|
||||
/// - `.phase`
|
||||
/// - `init(r:θ:)`
|
||||
public var polar: (length: RealType, phase: RealType) {
|
||||
(length, phase)
|
||||
}
|
||||
|
||||
/// Constructs a complex value from polar coordinates.
|
||||
///
|
||||
/// Edge cases:
|
||||
/// -
|
||||
/// If the phase is non-finite, but length is finite, this initializer fails and returns nil. In all other cases,
|
||||
/// a non-nil value is constructed.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `.length`
|
||||
/// - `.phase`
|
||||
/// - `.polar`
|
||||
public init?(length: RealType, phase: RealType) {
|
||||
guard phase.isFinite else {
|
||||
// There's no way to make sense of finite magnitude and non-finite phase.
|
||||
if length.isFinite { return nil }
|
||||
// r is infinite so phase doesn't matter.
|
||||
self = .infinity
|
||||
return
|
||||
}
|
||||
self.init(length * .cos(phase), length * .sin(phase))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Complex Numbers
|
||||
|
||||
This module provides a `Complex` number type generic over an underlying `RealType`:
|
||||
```swift
|
||||
1> import Complex
|
||||
2> let z = Complex(1,1) // z = 1 + i
|
||||
```
|
||||
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 `AdditiveArithmetic`).
|
||||
|
||||
### Dependencies:
|
||||
- The `ElementaryFunctions` module.
|
||||
|
||||
## Design notes
|
||||
|
||||
### Mixed real-complex arithmetic.
|
||||
It is tempting to define real-complex arithmetic operators, because we use them as
|
||||
shorthand all the time in mathematics: `z + x` or `2w`. They are not provided by the
|
||||
Complex module for two reasons:
|
||||
- Swift generally avoids heterogenous arithmetic operators
|
||||
- They lead to counter-intuitive behavior of type inference.
|
||||
For a concrete example of the second point, suppose that heterogeneous arithmetic
|
||||
operators existed, and consider the following snippet:
|
||||
```swift
|
||||
let a: RealType = 1
|
||||
let b = 2*a
|
||||
```
|
||||
what is the type of `b`?
|
||||
|
||||
If there is no type context, `b` is ambiguous; `2*a` could be interpreted as
|
||||
`Complex(2)*a` or as `RealType(2)*a`. That's fairly annoying on its own. However,
|
||||
suppose that we're in a `Complex` type context:
|
||||
```swift
|
||||
extension Complex {
|
||||
static func doSomething() {
|
||||
let a: RealType = 1
|
||||
let b = 2*a // type is inferred as Complex 🤪
|
||||
}
|
||||
}
|
||||
```
|
||||
This is a show-stopper for heterogeneous arithmetic operators in the short term.
|
||||
|
||||
### Infinity and nan
|
||||
C and C++ attempt to define precise semantics that interpret the sign of infinity and zero.
|
||||
This is occasionally useful, but it also results in a lot of extra work. The swift-numerics
|
||||
`Complex` type does not assign any semantic meaning to the sign of zero and infinity;
|
||||
`(±0,±0)`, are all considered to be encodings of the value zero. Similarly, `(±inf, y)`,
|
||||
`(x, ±inf)`, `(nan, y)` and `(x, nan)` are all considered to be encodings of a single
|
||||
exceptional value with infinite magnitude and undefined phase.
|
||||
|
||||
Because the phase is undefined, the `.real` and `.imag` properties return `.nan`
|
||||
|
||||
This decision may be revisited once users gain some experience working with the type
|
||||
to make sure that it's a tradeoff that we're happy with, but early experiments show that
|
||||
it greatly simplifies the implementation of some operations without significant tradeoffs
|
||||
in usability.
|
||||
|
||||
### The magnitude property
|
||||
The `Numeric` protocol requires a `.magnitude` property, but (deliberately) does not
|
||||
fully specify the semantics. The most obvious choice would be to use the Euclidean
|
||||
norm (`sqrt(real*real + imag*imag)`). However, in practice there are good reasons
|
||||
to use something else instead:
|
||||
|
||||
- The two-norm requires special care to avoid spurious overflow/underflow, but the
|
||||
naive expressions for the 1-norm or ∞-norm are always correct.
|
||||
- Even when care is used, near the overflow boundary the two-norm may not be
|
||||
representable. The ∞-norm in particular is always representable (because of this,
|
||||
the ∞-norm would seem to be the obvious alternative; it gives the nicest API surface).
|
||||
- Both the 1-norm and ∞-norm are much easier to compute for operators than the
|
||||
2-norm (O(n) vs. "no closed form expression, but usually O(n^3) iterative methods"),
|
||||
so it would be nice to establish a precedent of .magnitude binding one of these
|
||||
cheaper-to-compute norms.
|
||||
|
||||
The 2-norm still needs to be available, of course, because sometimes you need it.
|
||||
Presently, this functionality is accessed via the `.length` and `.unsafeLengthSquared`
|
||||
properties, but I expect that we will end up iterating on this aspect of the design.
|
||||
@@ -0,0 +1,414 @@
|
||||
//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A type that has elementary functions available.
|
||||
///
|
||||
/// An ["elementary function"][elfn] is a function built up from powers, roots,
|
||||
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
|
||||
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
|
||||
/// inverses.
|
||||
///
|
||||
/// Conformance to this protocol means that all of these building blocks are
|
||||
/// available as static functions on the type.
|
||||
///
|
||||
/// ```swift
|
||||
/// let x: Float = 1
|
||||
/// let y = Float.sin(x) // 0.84147096
|
||||
/// ```
|
||||
///
|
||||
/// There are three broad families of functions defined by `ElementaryFunctions`:
|
||||
/// - Exponential, trigonometric, and hyperbolic functions:
|
||||
/// `exp`, `expm1`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
|
||||
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
|
||||
/// `log`, `log1p`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and `atanh`.
|
||||
/// - Power and root functions:
|
||||
/// `pow`, `sqrt`, and `root`.
|
||||
///
|
||||
/// There is a second protocol, `RealFunctions`, which refines `ElementaryFunctions`
|
||||
/// and includes additional operations which are more commonly used specifically with real
|
||||
/// number types.
|
||||
///
|
||||
/// See Also:
|
||||
/// -
|
||||
/// - `RealFunctions`
|
||||
///
|
||||
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
|
||||
public protocol ElementaryFunctions {
|
||||
/// The [exponential function][wiki] e^x whose base `e` is the base of the natural logarithm.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `expm1()`
|
||||
/// - `exp2()` (for types conforming to `RealFunctions`)
|
||||
/// - `exp10()` (for types conforming to `RealFunctions`)
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
|
||||
static func exp(_ x: Self) -> Self
|
||||
|
||||
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from catastrophic
|
||||
/// cancellation and the result will not have full accuracy. The `.expm1(x)` function gives
|
||||
/// you a means to address this problem.
|
||||
///
|
||||
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x` is smaller
|
||||
/// than `.ulpOfOne`, this expression evaluates to `0.0`, when it should actually round to
|
||||
/// `2*x`. We can get a full-accuracy result by using the following instead:
|
||||
/// ```
|
||||
/// let expm1x = .expm1(x)
|
||||
/// return x*(expm1x + 1) + expm1x
|
||||
/// ```
|
||||
/// This re-written expression delivers an accurate result for all values of `x`, not just for
|
||||
/// small values.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp()`
|
||||
/// - `exp2()` (for types conforming to `RealFunctions`)
|
||||
/// - `exp10()` (for types conforming to `RealFunctions`)
|
||||
static func expm1(_ x: Self) -> Self
|
||||
|
||||
/// The [hyperbolic cosine][wiki] of `x`.
|
||||
/// ```
|
||||
/// e^x + e^-x
|
||||
/// cosh(x) = ------------
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `sinh()`
|
||||
/// - `tanh()`
|
||||
/// - `acosh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func cosh(_ x: Self) -> Self
|
||||
|
||||
/// The [hyperbolic sine][wiki] of `x`.
|
||||
/// ```
|
||||
/// e^x - e^-x
|
||||
/// sinh(x) = ------------
|
||||
/// 2
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cosh()`
|
||||
/// - `tanh()`
|
||||
/// - `asinh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func sinh(_ x: Self) -> Self
|
||||
|
||||
/// The [hyperbolic tangent][wiki] of `x`.
|
||||
/// ```
|
||||
/// sinh(x)
|
||||
/// tanh(x) = ---------
|
||||
/// cosh(x)
|
||||
/// ```
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cosh()`
|
||||
/// - `sinhh()`
|
||||
/// - `atanh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
|
||||
static func tanh(_ x: Self) -> Self
|
||||
|
||||
/// The [cosine][wiki] of `x`.
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `sin()`
|
||||
/// - `tan()`
|
||||
/// - `acos()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
|
||||
static func cos(_ x: Self) -> Self
|
||||
|
||||
|
||||
/// The [sine][wiki] of `x`.
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cos()`
|
||||
/// - `tan()`
|
||||
/// - `asin()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Sine
|
||||
static func sin(_ x: Self) -> Self
|
||||
|
||||
/// The [tangent][wiki] of `x`.
|
||||
///
|
||||
/// For real types, `x` may be interpreted as an angle measured in radians.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `cos()`
|
||||
/// - `sin()`
|
||||
/// - `atan()`
|
||||
/// - `atan2(y:x:)` (for types conforming to `RealFunctions`)
|
||||
/// ```
|
||||
/// sin(x)
|
||||
/// tan(x) = --------
|
||||
/// cos(x)
|
||||
/// ```
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
|
||||
static func tan(_ x: Self) -> Self
|
||||
|
||||
/// The [natural logarithm][wiki] of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `log1p()`
|
||||
/// - `log2()` (for types conforming to `RealFunctions`)
|
||||
/// - `log10()` (for types conforming to `RealFunctions`)
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
|
||||
static func log(_ x: Self) -> Self
|
||||
|
||||
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `log()`
|
||||
/// - `log2()` (for types conforming to `RealFunctions`)
|
||||
/// - `log10()` (for types conforming to `RealFunctions`)
|
||||
static func log1p(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic cosine][wiki] of `x`.
|
||||
/// ```
|
||||
/// cosh(acosh(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `asinh()`
|
||||
/// - `atanh()`
|
||||
/// - `cosh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func acosh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic sine][wiki] of `x`.
|
||||
/// ```
|
||||
/// sinh(asinh(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acosh()`
|
||||
/// - `atanh()`
|
||||
/// - `sinh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func asinh(_ x: Self) -> Self
|
||||
|
||||
/// The [inverse hyperbolic tangent][wiki] of `x`.
|
||||
/// ```
|
||||
/// tanh(atanh(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acosh()`
|
||||
/// - `asinh()`
|
||||
/// - `tanh()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
|
||||
static func atanh(_ x: Self) -> Self
|
||||
|
||||
/// The [arccosine][wiki] (inverse cosine) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// ```
|
||||
/// cos(acos(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `asin()`
|
||||
/// - `atan()`
|
||||
/// - `cos()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func acos(_ x: Self) -> Self
|
||||
|
||||
/// The [arcsine][wiki] (inverse sine) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// ```
|
||||
/// sin(asin(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acos()`
|
||||
/// - `atan()`
|
||||
/// - `sin()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func asin(_ x: Self) -> Self
|
||||
|
||||
/// The [arctangent][wiki] (inverse tangent) of `x`.
|
||||
///
|
||||
/// For real types, the result may be interpreted as an angle measured in radians.
|
||||
/// ```
|
||||
/// tan(atan(x)) ≅ x
|
||||
/// ```
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `acos()`
|
||||
/// - `asin()`
|
||||
/// - `atan2()` (for types conforming to `RealFunctions`)
|
||||
/// - `tan()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
|
||||
static func atan(_ x: Self) -> Self
|
||||
|
||||
/// exp(y * log(x)) computed with additional internal precision.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `sqrt()`
|
||||
/// - `root()`
|
||||
///
|
||||
static func pow(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// `x` raised to the nth power.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `sqrt()`
|
||||
/// - `root()`
|
||||
///
|
||||
static func pow(_ x: Self, _ n: Int) -> Self
|
||||
|
||||
/// The [square root][wiki] of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `pow()`
|
||||
/// - `root()`
|
||||
///
|
||||
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
|
||||
static func sqrt(_ x: Self) -> Self
|
||||
|
||||
/// The nth root of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `pow()`
|
||||
/// - `sqrt()`
|
||||
///
|
||||
static func root(_ x: Self, _ n: Int) -> Self
|
||||
}
|
||||
|
||||
public protocol RealFunctions: ElementaryFunctions {
|
||||
/// `atan(y/x)`, with sign selected according to the quadrant of `(x, y)`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `atan()`
|
||||
static func atan2(y: Self, x: Self) -> Self
|
||||
|
||||
/// The error function evaluated at `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `erfc()`
|
||||
static func erf(_ x: Self) -> Self
|
||||
|
||||
/// The complimentary error function evaluated at `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `erf()`
|
||||
static func erfc(_ x: Self) -> Self
|
||||
|
||||
/// 2^x
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp()`
|
||||
/// - `expm1()`
|
||||
/// - `exp10()`
|
||||
/// - `log2()`
|
||||
/// - `pow()`
|
||||
static func exp2(_ x: Self) -> Self
|
||||
|
||||
/// 10^x
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp()`
|
||||
/// - `expm1()`
|
||||
/// - `exp2()`
|
||||
/// - `log10()`
|
||||
/// - `pow()`
|
||||
static func exp10(_ x: Self) -> Self
|
||||
|
||||
/// `sqrt(x*x + y*y)`, computed in a manner that avoids spurious overflow or underflow.
|
||||
static func hypot(_ x: Self, _ y: Self) -> Self
|
||||
|
||||
/// The gamma function Γ(x).
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `logGamma()`
|
||||
/// - `signGamma()`
|
||||
static func gamma(_ x: Self) -> Self
|
||||
|
||||
/// The base-2 logarithm of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp2()`
|
||||
/// - `log()`
|
||||
/// - `log1p()`
|
||||
/// - `log10()`
|
||||
static func log2(_ x: Self) -> Self
|
||||
|
||||
/// The base-10 logarithm of `x`.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `exp10()`
|
||||
/// - `log()`
|
||||
/// - `log1p()`
|
||||
/// - `log2()`
|
||||
static func log10(_ x: Self) -> Self
|
||||
|
||||
/// The logarithm of the absolute value of the gamma function, log(|Γ(x)|).
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `gamma()`
|
||||
/// - `signGamma()`
|
||||
static func logGamma(_ x: Self) -> Self
|
||||
}
|
||||
|
||||
/// A type that models the real numbers.
|
||||
///
|
||||
/// Types conforming to this protocol provide the arithmetic and utility operations defined by
|
||||
/// the `FloatingPoint` protocol, and provide all of the math functions defined by the
|
||||
/// `ElementaryFunctions` and `RealFunctions` protocols. This protocol does not
|
||||
/// add any additional conformances itself, but is very useful as a protocol against which to
|
||||
/// write generic code. For example, we can naturally write a generic version of the a sigmoid
|
||||
/// function:
|
||||
/// ```
|
||||
/// func sigmoid<T: Real>(_ x: T) -> T {
|
||||
/// return 1/(1 + .exp(-x))
|
||||
/// }
|
||||
/// ```
|
||||
public protocol Real: FloatingPoint, RealFunctions {
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//===--- Implementations.swift --------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// While `Real` does not provide any additional customization points,
|
||||
// it does allow us to default the implementation of a few operations,
|
||||
// and also provides `signGamma`.
|
||||
extension Real {
|
||||
// Most math libraries do not provide exp10, so we need a default impl.
|
||||
@_transparent
|
||||
public static func exp10(_ x: Self) -> Self {
|
||||
return pow(10, x)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func root(_ x: Self, _ n: Int) -> Self {
|
||||
guard x >= 0 || n % 2 != 0 else { return .nan }
|
||||
// TODO: this implementation is not quite correct, because n may be
|
||||
// rounded in conversion to Self. This only effects very extreme cases,
|
||||
// so we'll leave it alone for now.
|
||||
return Self(signOf: x, magnitudeOf: pow(x.magnitude, 1/Self(n)))
|
||||
}
|
||||
|
||||
/// The sign of the gamma function, Γ(x).
|
||||
///
|
||||
/// For `x >= 0`, `signGamma(x)` is `.plus`. For negative `x`, `signGamma(x)` is `.plus`
|
||||
/// when `x` is an integer, and otherwise it is `.minus` whenver `trunc(x)` is even, and `.plus`
|
||||
/// when `trunc(x)` is odd.
|
||||
///
|
||||
/// This function is mainly used together with `logGamma`, which computes the logarithm of the
|
||||
/// absolute value of Γ(x), to recover the sign information.
|
||||
///
|
||||
/// See also:
|
||||
/// -
|
||||
/// - `gamma()`
|
||||
/// - `logGamma()`
|
||||
public static func signGamma(_ x: Self) -> FloatingPointSign {
|
||||
// Gamma is strictly positive for x >= 0.
|
||||
if x >= 0 { return .plus }
|
||||
// For negative x, we arbitrarily choose to assign a sign of .plus to the
|
||||
// poles.
|
||||
let trunc = x.rounded(.towardZero)
|
||||
if x == trunc { return .plus }
|
||||
// Otherwise, signGamma is .minus if the integral part of x is even.
|
||||
return trunc.isEven ? .minus : .plus
|
||||
}
|
||||
|
||||
// Determines if this value is even, assuming that it is an integer.
|
||||
@inline(__always)
|
||||
private var isEven: Bool {
|
||||
if Self.radix == 2 {
|
||||
// For binary types, we can just check if x/2 is an integer. This works
|
||||
// because x/2 is always computed exactly.
|
||||
let half = self/2
|
||||
return half == half.rounded(.towardZero)
|
||||
} else {
|
||||
// For decimal types, it's not quite that simple, because x/2 is not
|
||||
// necessarily computed exactly. As an example, suppose that we had a
|
||||
// decimal type with a one digit significand, and self = 7. Then self/2
|
||||
// would round to 4, and we would (wrongly) conclude that it was an
|
||||
// integer, and hence that self was even.
|
||||
//
|
||||
// Instead, for decimal types, we check if 2*trunc(self/2) == self,
|
||||
// using an FMA; this is always correct; this approach works for any
|
||||
// radix, but the previous method is more efficient for radix == 2.
|
||||
let half = self/2
|
||||
return self.addingProduct(-2, half.rounded(.towardZero)) == 0
|
||||
}
|
||||
}
|
||||
|
||||
@_transparent
|
||||
public static func sqrt(_ x: Self) -> Self {
|
||||
return x.squareRoot()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Elementary Functions
|
||||
|
||||
This module implements [SE-0246]. It is being implemented here first to work around a
|
||||
few difficulties that blocked adding these operations to the standard library for 5.1:
|
||||
|
||||
- Swift does not yet have a way to back-deploy protocol conformances; this prevents
|
||||
making this useful feature available on older Apple OS targets.
|
||||
|
||||
- The lack of means to back-deploy prevents obsoleting the existing concrete
|
||||
math functions defined in the Darwin (Apple platforms), Glibc (Linux), and MSVCRT
|
||||
(Windows) modules.
|
||||
|
||||
- There is an outstanding bug with name resolution, which causes the new static functions
|
||||
(`Float.sin`) to shadow the existing free functions (`sin(_ x: Float) -> Float`) even
|
||||
in contexts where static functions are not allowed, leading to a number of spurious errors.
|
||||
See https://github.com/apple/swift/pull/25316 for discussion of how to fix this.
|
||||
|
||||
- There are some typechecker performance regressions (partially resulting from the issues
|
||||
described above).
|
||||
|
||||
Placing this module in swift-numerics first gives the community a chance to address
|
||||
some of the compiler limitations that this feature ran into *before* it lands in the standard
|
||||
library (avoiding unnecessary source churn for projects that use these features), while also
|
||||
making it available *now*, including back-deployment to older Apple OS targets.
|
||||
|
||||
Further details can be found in the [SE-0246 proposal document][SE-0246].
|
||||
|
||||
[SE-0246]: https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md
|
||||
|
||||
### Dependencies:
|
||||
- The C standard math library (`libm`) via the `NumericShims` target.
|
||||
@@ -0,0 +1,138 @@
|
||||
//===--- ScalarConformances.swift -----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NumericsShims
|
||||
|
||||
extension Float: Real {
|
||||
@_transparent public static func cos(_ x: Float) -> Float { return swift_cosf(x) }
|
||||
@_transparent public static func sin(_ x: Float) -> Float { return swift_sinf(x) }
|
||||
@_transparent public static func tan(_ x: Float) -> Float { return swift_tanf(x) }
|
||||
@_transparent public static func acos(_ x: Float) -> Float { return swift_acosf(x) }
|
||||
@_transparent public static func asin(_ x: Float) -> Float { return swift_asinf(x) }
|
||||
@_transparent public static func atan(_ x: Float) -> Float { return swift_atanf(x) }
|
||||
@_transparent public static func cosh(_ x: Float) -> Float { return swift_coshf(x) }
|
||||
@_transparent public static func sinh(_ x: Float) -> Float { return swift_sinhf(x) }
|
||||
@_transparent public static func tanh(_ x: Float) -> Float { return swift_tanhf(x) }
|
||||
@_transparent public static func acosh(_ x: Float) -> Float { return swift_acoshf(x) }
|
||||
@_transparent public static func asinh(_ x: Float) -> Float { return swift_asinhf(x) }
|
||||
@_transparent public static func atanh(_ x: Float) -> Float { return swift_atanhf(x) }
|
||||
@_transparent public static func exp(_ x: Float) -> Float { return swift_expf(x) }
|
||||
@_transparent public static func expm1(_ x: Float) -> Float { return swift_expm1f(x) }
|
||||
@_transparent public static func log(_ x: Float) -> Float { return swift_logf(x) }
|
||||
@_transparent public static func log1p(_ x: Float) -> Float { return swift_log1pf(x) }
|
||||
@_transparent public static func pow(_ x: Float, _ y: Float) -> Float {
|
||||
guard x >= 0 else { return .nan }
|
||||
return swift_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 swift_powf(x, Float(n))
|
||||
}
|
||||
@_transparent public static func atan2(y: Float, x: Float) -> Float { return swift_atan2f(y, x) }
|
||||
@_transparent public static func erf(_ x: Float) -> Float { return swift_erff(x) }
|
||||
@_transparent public static func erfc(_ x: Float) -> Float { return swift_erfcf(x) }
|
||||
@_transparent public static func exp2(_ x: Float) -> Float { return swift_exp2f(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_silgen_name("__exp10f") public static func exp10(_ x: Float) -> Float
|
||||
#endif
|
||||
@_transparent public static func hypot(_ x: Float, _ y: Float) -> Float { return swift_hypotf(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float) -> Float { return swift_gammaf(x) }
|
||||
@_transparent public static func log2(_ x: Float) -> Float { return swift_log2f(x) }
|
||||
@_transparent public static func log10(_ x: Float) -> Float { return swift_log10f(x) }
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Float) -> Float { return swift_lgammaf(x) }
|
||||
#endif
|
||||
}
|
||||
|
||||
extension Double: Real {
|
||||
@_transparent public static func cos(_ x: Double) -> Double { return swift_cos(x) }
|
||||
@_transparent public static func sin(_ x: Double) -> Double { return swift_sin(x) }
|
||||
@_transparent public static func tan(_ x: Double) -> Double { return swift_tan(x) }
|
||||
@_transparent public static func acos(_ x: Double) -> Double { return swift_acos(x) }
|
||||
@_transparent public static func asin(_ x: Double) -> Double { return swift_asin(x) }
|
||||
@_transparent public static func atan(_ x: Double) -> Double { return swift_atan(x) }
|
||||
@_transparent public static func cosh(_ x: Double) -> Double { return swift_cosh(x) }
|
||||
@_transparent public static func sinh(_ x: Double) -> Double { return swift_sinh(x) }
|
||||
@_transparent public static func tanh(_ x: Double) -> Double { return swift_tanh(x) }
|
||||
@_transparent public static func acosh(_ x: Double) -> Double { return swift_acosh(x) }
|
||||
@_transparent public static func asinh(_ x: Double) -> Double { return swift_asinh(x) }
|
||||
@_transparent public static func atanh(_ x: Double) -> Double { return swift_atanh(x) }
|
||||
@_transparent public static func exp(_ x: Double) -> Double { return swift_exp(x) }
|
||||
@_transparent public static func expm1(_ x: Double) -> Double { return swift_expm1(x) }
|
||||
@_transparent public static func log(_ x: Double) -> Double { return swift_log(x) }
|
||||
@_transparent public static func log1p(_ x: Double) -> Double { return swift_log1p(x) }
|
||||
@_transparent public static func pow(_ x: Double, _ y: Double) -> Double {
|
||||
guard x >= 0 else { return .nan }
|
||||
return swift_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 swift_pow(x, Double(n))
|
||||
}
|
||||
@_transparent public static func atan2(y: Double, x: Double) -> Double { return swift_atan2(y, x) }
|
||||
@_transparent public static func erf(_ x: Double) -> Double { return swift_erf(x) }
|
||||
@_transparent public static func erfc(_ x: Double) -> Double { return swift_erfc(x) }
|
||||
@_transparent public static func exp2(_ x: Double) -> Double { return swift_exp2(x) }
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
|
||||
@_silgen_name("__exp10") public static func exp10(_ x: Double) -> Double
|
||||
#endif
|
||||
@_transparent public static func hypot(_ x: Double, _ y: Double) -> Double { return swift_hypot(x, y) }
|
||||
@_transparent public static func gamma(_ x: Double) -> Double { return swift_gamma(x) }
|
||||
@_transparent public static func log2(_ x: Double) -> Double { return swift_log2(x) }
|
||||
@_transparent public static func log10(_ x: Double) -> Double { return swift_log10(x) }
|
||||
#if !os(Windows)
|
||||
@_transparent public static func logGamma(_ x: Double) -> Double { return swift_lgamma(x) }
|
||||
#endif
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: Real {
|
||||
@_transparent public static func cos(_ x: Float80) -> Float80 { return swift_cosl(x) }
|
||||
@_transparent public static func sin(_ x: Float80) -> Float80 { return swift_sinl(x) }
|
||||
@_transparent public static func tan(_ x: Float80) -> Float80 { return swift_tanl(x) }
|
||||
@_transparent public static func acos(_ x: Float80) -> Float80 { return swift_acosl(x) }
|
||||
@_transparent public static func asin(_ x: Float80) -> Float80 { return swift_asinl(x) }
|
||||
@_transparent public static func atan(_ x: Float80) -> Float80 { return swift_atanl(x) }
|
||||
@_transparent public static func cosh(_ x: Float80) -> Float80 { return swift_coshl(x) }
|
||||
@_transparent public static func sinh(_ x: Float80) -> Float80 { return swift_sinhl(x) }
|
||||
@_transparent public static func tanh(_ x: Float80) -> Float80 { return swift_tanhl(x) }
|
||||
@_transparent public static func acosh(_ x: Float80) -> Float80 { return swift_acoshl(x) }
|
||||
@_transparent public static func asinh(_ x: Float80) -> Float80 { return swift_asinhl(x) }
|
||||
@_transparent public static func atanh(_ x: Float80) -> Float80 { return swift_atanhl(x) }
|
||||
@_transparent public static func exp(_ x: Float80) -> Float80 { return swift_expl(x) }
|
||||
@_transparent public static func expm1(_ x: Float80) -> Float80 { return swift_expm1l(x) }
|
||||
@_transparent public static func log(_ x: Float80) -> Float80 { return swift_logl(x) }
|
||||
@_transparent public static func log1p(_ x: Float80) -> Float80 { return swift_log1pl(x) }
|
||||
@_transparent public static func pow(_ x: Float80, _ y: Float80) -> Float80 {
|
||||
guard x >= 0 else { return .nan }
|
||||
return swift_powl(x, y)
|
||||
}
|
||||
@_transparent public static func pow(_ x: Float80, _ n: Int) -> Float80 {
|
||||
return swift_powl(x, Float80(n))
|
||||
}
|
||||
@_transparent public static func atan2(y: Float80, x: Float80) -> Float80 { return swift_atan2l(y, x) }
|
||||
@_transparent public static func erf(_ x: Float80) -> Float80 { return swift_erfl(x) }
|
||||
@_transparent public static func erfc(_ x: Float80) -> Float80 { return swift_erfcl(x) }
|
||||
@_transparent public static func exp2(_ x: Float80) -> Float80 { return swift_exp2l(x) }
|
||||
@_transparent public static func hypot(_ x: Float80, _ y: Float80) -> Float80 { return swift_hypotl(x, y) }
|
||||
@_transparent public static func gamma(_ x: Float80) -> Float80 { return swift_gammal(x) }
|
||||
@_transparent public static func log2(_ x: Float80) -> Float80 { return swift_log2l(x) }
|
||||
@_transparent public static func log10(_ x: Float80) -> Float80 { return swift_log10l(x) }
|
||||
@_transparent public static func logGamma(_ x: Float80) -> Float80 { return swift_lgammal(x) }
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
//===--- NumericsShims.c --------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// This file exists only to trigger the NumericShims module to build; without
|
||||
// it swiftpm won't build anything, and then the shims are not available for
|
||||
// the modules that need them.
|
||||
|
||||
// If any shims are added that are not pure header inlines, whatever runtime
|
||||
// support they require can be added to this file.
|
||||
|
||||
#include "NumericsShims.h"
|
||||
@@ -0,0 +1,351 @@
|
||||
//===--- NumericsShims.h --------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#define HEADER_SHIM static inline __attribute__((__always_inline__))
|
||||
|
||||
// MARK: - math functions for float
|
||||
|
||||
HEADER_SHIM float swift_cosf(float x) {
|
||||
return __builtin_cosf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_sinf(float x) {
|
||||
return __builtin_sinf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_tanf(float x) {
|
||||
return __builtin_tanf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_acosf(float x) {
|
||||
return __builtin_acosf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_asinf(float x) {
|
||||
return __builtin_asinf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_atanf(float x) {
|
||||
return __builtin_atanf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_coshf(float x) {
|
||||
return __builtin_coshf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_sinhf(float x) {
|
||||
return __builtin_sinhf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_tanhf(float x) {
|
||||
return __builtin_tanhf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_acoshf(float x) {
|
||||
return __builtin_acoshf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_asinhf(float x) {
|
||||
return __builtin_asinhf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_atanhf(float x) {
|
||||
return __builtin_atanhf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_expf(float x) {
|
||||
return __builtin_expf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_expm1f(float x) {
|
||||
return __builtin_expm1f(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_logf(float x) {
|
||||
return __builtin_logf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_log1pf(float x) {
|
||||
return __builtin_log1pf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_powf(float x, float y) {
|
||||
return __builtin_powf(x, y);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_atan2f(float y, float x) {
|
||||
return __builtin_atan2f(y, x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_erff(float x) {
|
||||
return __builtin_erff(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_erfcf(float x) {
|
||||
return __builtin_erfcf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_exp2f(float x) {
|
||||
return __builtin_exp2f(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_hypotf(float x, float y) {
|
||||
#if defined(_WIN32)
|
||||
extern float _hypotf(float, float);
|
||||
return _hypotf(x, y);
|
||||
#else
|
||||
return __builtin_hypotf(x, y);
|
||||
#endif
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_gammaf(float x) {
|
||||
return __builtin_tgammaf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_log2f(float x) {
|
||||
return __builtin_log2f(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM float swift_log10f(float x) {
|
||||
return __builtin_log10f(x);
|
||||
}
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM float swift_lgammaf(float x) {
|
||||
#if __APPLE__
|
||||
extern float lgammaf_r(float, int *);
|
||||
#endif
|
||||
int _;
|
||||
return lgammaf_r(x, &_);
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - math functions for double
|
||||
|
||||
HEADER_SHIM double swift_cos(double x) {
|
||||
return __builtin_cos(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_sin(double x) {
|
||||
return __builtin_sin(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_tan(double x) {
|
||||
return __builtin_tan(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_acos(double x) {
|
||||
return __builtin_acos(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_asin(double x) {
|
||||
return __builtin_asin(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_atan(double x) {
|
||||
return __builtin_atan(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_cosh(double x) {
|
||||
return __builtin_cosh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_sinh(double x) {
|
||||
return __builtin_sinh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_tanh(double x) {
|
||||
return __builtin_tanh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_acosh(double x) {
|
||||
return __builtin_acosh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_asinh(double x) {
|
||||
return __builtin_asinh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_atanh(double x) {
|
||||
return __builtin_atanh(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_exp(double x) {
|
||||
return __builtin_exp(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_expm1(double x) {
|
||||
return __builtin_expm1(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_log(double x) {
|
||||
return __builtin_log(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_log1p(double x) {
|
||||
return __builtin_log1p(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_pow(double x, double y) {
|
||||
return __builtin_pow(x, y);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_atan2(double y, double x) {
|
||||
return __builtin_atan2(y, x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_erf(double x) {
|
||||
return __builtin_erf(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_erfc(double x) {
|
||||
return __builtin_erfc(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_exp2(double x) {
|
||||
return __builtin_exp2(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_hypot(double x, double y) {
|
||||
return __builtin_hypot(x, y);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_gamma(double x) {
|
||||
return __builtin_tgamma(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_log2(double x) {
|
||||
return __builtin_log2(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM double swift_log10(double x) {
|
||||
return __builtin_log10(x);
|
||||
}
|
||||
|
||||
#if !defined _WIN32
|
||||
HEADER_SHIM double swift_lgamma(double x) {
|
||||
#if __APPLE__
|
||||
extern double lgamma_r(double, int *);
|
||||
#endif
|
||||
int _;
|
||||
return lgamma_r(x, &_);
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - math functions for float80
|
||||
#if !defined _WIN32 && (defined __i386__ || defined __x86_64__)
|
||||
HEADER_SHIM long double swift_cosl(long double x) {
|
||||
return __builtin_cosl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_sinl(long double x) {
|
||||
return __builtin_sinl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_tanl(long double x) {
|
||||
return __builtin_tanl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_acosl(long double x) {
|
||||
return __builtin_acosl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_asinl(long double x) {
|
||||
return __builtin_asinl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_atanl(long double x) {
|
||||
return __builtin_atanl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_coshl(long double x) {
|
||||
return __builtin_coshl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_sinhl(long double x) {
|
||||
return __builtin_sinhl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_tanhl(long double x) {
|
||||
return __builtin_tanhl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_acoshl(long double x) {
|
||||
return __builtin_acoshl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_asinhl(long double x) {
|
||||
return __builtin_asinhl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_atanhl(long double x) {
|
||||
return __builtin_atanhl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_expl(long double x) {
|
||||
return __builtin_expl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_expm1l(long double x) {
|
||||
return __builtin_expm1l(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_logl(long double x) {
|
||||
return __builtin_logl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_log1pl(long double x) {
|
||||
return __builtin_log1pl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_powl(long double x, long double y) {
|
||||
return __builtin_powl(x, y);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_atan2l(long double y, long double x) {
|
||||
return __builtin_atan2l(y, x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_erfl(long double x) {
|
||||
return __builtin_erfl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_erfcl(long double x) {
|
||||
return __builtin_erfcl(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_exp2l(long double x) {
|
||||
return __builtin_exp2l(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_hypotl(long double x, long double y) {
|
||||
return __builtin_hypotl(x, y);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_gammal(long double x) {
|
||||
return __builtin_tgammal(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_log2l(long double x) {
|
||||
return __builtin_log2l(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_log10l(long double x) {
|
||||
return __builtin_log10l(x);
|
||||
}
|
||||
|
||||
HEADER_SHIM long double swift_lgammal(long double x) {
|
||||
extern long double lgammal_r(long double, int *);
|
||||
int _;
|
||||
return lgammal_r(x, &_);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,64 @@
|
||||
//===--- ComplexTests.swift -----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Complex
|
||||
|
||||
final class ComplexTests: XCTestCase {
|
||||
|
||||
// Double-precision test cases from Baudin & Smith's "A Robust Complex Division in Scilab".
|
||||
func testDivide_BaudinSmith() {
|
||||
XCTAssertEqual(Complex(1,1)/Complex(1, 0x1p1023),
|
||||
Complex(0x1p-1023, -0x1p-1023))
|
||||
XCTAssertEqual(Complex(1,1)/Complex(0x1p-1023, 0x1p-1023),
|
||||
Complex(0x1p1023))
|
||||
XCTAssertEqual(Complex(0x1p1023, 0x1p1023)/Complex(1,1),
|
||||
Complex(0x1.0p1023))
|
||||
XCTAssertEqual(Complex(0x1p-347, 0x1p-54)/Complex(0x1p-1037, 0x1p-1058),
|
||||
Complex(3.8981256045591133e289, 8.174961907852353577e295))
|
||||
XCTAssertEqual(Complex(0x1p-1074, 0x1p-1074)/Complex(0x1p-1073, 0x1p-1074),
|
||||
Complex(0.6, 0.2))
|
||||
XCTAssertEqual(Complex(0x1p1015, 0x1p-989)/Complex(0x1p1023, 0x1p1023),
|
||||
Complex(0.001953125, -0.001953125))
|
||||
XCTAssertEqual(Complex(0x1p-622, 0x1p-1071)/Complex(0x1p-343, 0x1p-798),
|
||||
Complex(1.02951151789360578e-84, 6.97145987515076231e-220))
|
||||
}
|
||||
|
||||
func testDivide_BaudinSmithApprox() {
|
||||
// Policy: we deliberately do not try to get these cases from Baudin and
|
||||
// Smith "right"; instead we simply want an answer that's as accurate
|
||||
// (in the complex norm) as can be expected. We don't care what happens
|
||||
// to the tiny component of the result.
|
||||
func closeEnough(_ a: Complex<Double>, _ b: Complex<Double>) -> Bool {
|
||||
return (a - b).magnitude < max(a.magnitude, b.magnitude) * 0x1p-50
|
||||
}
|
||||
XCTAssert(closeEnough(Complex(0x1p1023, 0x1p-1023)/Complex(0x1p677, 0x1p-677),
|
||||
Complex(0x1p346, -0x1p-1008)))
|
||||
XCTAssert(closeEnough(Complex(0x1p1020, 0x1p-844)/Complex(0x1p656, 0x1p-780),
|
||||
Complex(0x1p364, -0x1p-1072)))
|
||||
XCTAssert(closeEnough(Complex(0x1p-71, 0x1p1021)/Complex(0x1p1001, 0x1p-323),
|
||||
Complex(0x1p-1072, 0x1p20)))
|
||||
}
|
||||
|
||||
static var allTests = [
|
||||
("testDivide_BaudinSmith", testDivide_BaudinSmith),
|
||||
("testDivide_BaudinSmithApprox", testDivide_BaudinSmithApprox),
|
||||
]
|
||||
}
|
||||
|
||||
#if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
|
||||
public func allTests() -> [XCTestCaseEntry] {
|
||||
return [
|
||||
testCase(ComplexTests.allTests),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,18 @@
|
||||
#if !canImport(ObjectiveC)
|
||||
import XCTest
|
||||
|
||||
extension ComplexTests {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__ComplexTests = [
|
||||
("testEquality", testEquality),
|
||||
]
|
||||
}
|
||||
|
||||
public func __allTests() -> [XCTestCaseEntry] {
|
||||
return [
|
||||
testCase(ComplexTests.__allTests__ComplexTests),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,128 @@
|
||||
//===--- ElementaryFunctionTests.swift ------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2019 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import ElementaryFunctions
|
||||
|
||||
#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.expm1(0.375))
|
||||
sanityCheck(-0.980829253011726236856451127452003999, Self.log(0.375))
|
||||
sanityCheck(0.3184537311185346158102472135905995955, Self.log1p(0.375))
|
||||
sanityCheck(-0.7211247851537041911608191553900547941, Self.root(-0.375, 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))
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
#if !os(Windows)
|
||||
sanityCheck( -0.11775527074107877445136203331798850, Self.logGamma(1.375))
|
||||
XCTAssertEqual(.plus, Self.signGamma(1.375))
|
||||
XCTAssertEqual(.minus, Self.signGamma(-2.375))
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
|
||||
func testFloat() {
|
||||
Float.elementaryFunctionTests()
|
||||
Float.realFunctionTests()
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
Double.elementaryFunctionTests()
|
||||
Double.realFunctionTests()
|
||||
}
|
||||
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
func testFloat80() {
|
||||
Float80.elementaryFunctionTests()
|
||||
Float80.realFunctionTests()
|
||||
}
|
||||
|
||||
static var allTests = [
|
||||
("testFloat", testFloat),
|
||||
("testDouble", testDouble),
|
||||
("testFloat80", testFloat80),
|
||||
]
|
||||
#else
|
||||
static var allTests = [
|
||||
("testFloat", testFloat),
|
||||
("testDouble", testDouble),
|
||||
]
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
|
||||
public func allTests() -> [XCTestCaseEntry] {
|
||||
return [
|
||||
testCase(ComplexTests.allTests),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
#if !canImport(ObjectiveC)
|
||||
import XCTest
|
||||
|
||||
extension ElementaryFunctionTests {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__ElementaryFunctionTests = [
|
||||
("testDouble", testDouble),
|
||||
("testFloat", testFloat),
|
||||
("testFloat80", testFloat80),
|
||||
]
|
||||
}
|
||||
|
||||
public func __allTests() -> [XCTestCaseEntry] {
|
||||
return [
|
||||
testCase(ElementaryFunctionTests.__allTests__ElementaryFunctionTests),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
import XCTest
|
||||
|
||||
import ComplexTests
|
||||
import ElementaryFunctionTests
|
||||
|
||||
var tests = [XCTestCaseEntry]()
|
||||
tests += ComplexTests.__allTests()
|
||||
tests += ElementaryFunctionTests.__allTests()
|
||||
|
||||
XCTMain(tests)
|
||||
Reference in new issue
Block a user