Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions Sources/RealModule/Angle.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
//===--- Angle.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// A wrapper type for angle operations and functions
///
/// All trigonometric functions expect the argument to be passed as radians (Real), but this is not enforced by the type system.
/// This type serves exactly this purpose, and can be seen as an alternative to the underlying Real implementation.
public struct Angle<T: Real> {
public var radians: T
public init(radians: T) { self.radians = radians }
public static func radians(_ val: T) -> Angle<T> { .init(radians: val) }

public var degrees: T { radians * 180 / .pi }
public init(degrees: T) {
let normalized = normalize(degrees, limit: 180)
self.init(radians: normalized * .pi / 180)
}
public static func degrees(_ val: T) -> Angle<T> { .init(degrees: val) }
}

public extension ElementaryFunctions
where Self: Real {
/// See also:
/// -
/// `ElementaryFunctions.cos()`
static func cos(_ angle: Angle<Self>) -> Self {
let normalizedRadians = normalize(angle.radians, limit: .pi)

if -.pi/4 < normalizedRadians && normalizedRadians < .pi/4 {
return Self.cos(normalizedRadians)
}

if normalizedRadians > 3 * .pi / 4 || normalizedRadians < -3 * .pi / 4 {
return -Self.cos(.pi - normalizedRadians)
}

if normalizedRadians >= 0 {
return Self.sin(.pi/2 - normalizedRadians)
}

return Self.sin(normalizedRadians + .pi / 2)
}

/// See also:
/// -
/// `ElementaryFunctions.sin()`
static func sin(_ angle: Angle<Self>) -> Self {
let normalizedRadians = normalize(angle.radians, limit: .pi)

if .pi / 4 < normalizedRadians && normalizedRadians < 3 * .pi / 4 {
return Self.sin(normalizedRadians)
}

if -3 * .pi / 4 < normalizedRadians && normalizedRadians < -.pi / 4 {
return -Self.sin(-normalizedRadians)
}

if normalizedRadians > 3 * .pi / 4 {
return Self.sin(.pi - normalizedRadians)
}

if normalizedRadians < -3 * .pi / 4 {
return -Self.sin(.pi + normalizedRadians)
}

return Self.sin(normalizedRadians)
}

/// See also:
/// -
/// `ElementaryFunctions.tan()`
static func tan(_ angle: Angle<Self>) -> Self {
let sine = sin(angle)
let cosine = cos(angle)

guard cosine != 0 else {
var result = Self.infinity
if sine.sign == .minus {
result.negate()
}
return result
}

return sine / cosine
}
}

public extension Angle {
/// See also:
/// -
/// `ElementaryFunctions.acos()`
static func acos(_ x: T) -> Self { Angle.radians(T.acos(x)) }

/// See also:
/// -
/// `ElementaryFunctions.asin()`
static func asin(_ x: T) -> Self { Angle.radians(T.asin(x)) }

/// See also:
/// -
/// `ElementaryFunctions.atan()`
static func atan(_ x: T) -> Self { Angle.radians(T.atan(x)) }

/// See also:
/// -
/// `RealFunctions.atan2()`
static func atan2(y: T, x: T) -> Self { Angle.radians(T.atan2(y: y, x: x)) }
}

extension Angle: AdditiveArithmetic {
public static var zero: Angle<T> { .radians(0) }

public static func + (lhs: Angle<T>, rhs: Angle<T>) -> Angle<T> {
Angle(radians: lhs.radians + rhs.radians)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems unfortunate to me that adding two angles specified in degrees incurs rounding error seven times if I want the result in degrees. I think this dedicated type needs to store values given in degrees as-is if it offers such arithmetic.

Copy link
Author

@jkalias jkalias Dec 14, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I intended with my earlier comment, so degrees and radians are stored separately.
#169 (comment)

We could then switch on all operations performed on the input and essentially handle three cases:

  • degrees with degrees -> perform operation in degrees
  • radians with radians -> perform operation in radians
  • mixed units -> perform in a common unit

I'm not sure whether people agree on that

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 That would yield a superior result in the case of operations performed entirely in degrees or radians.

I wonder if there are alternative designs that can improve the result when working with both degrees and radians. If the type stored both radians and degrees, for example, then you could store the result of "90 degrees plus 1 radian" exactly. I haven't thought through the remainder of the design, but I offer it for your consideration here.

}

public static func += (lhs: inout Angle<T>, rhs: Angle<T>) {
lhs.radians += rhs.radians
}

public static func - (lhs: Angle<T>, rhs: Angle<T>) -> Angle<T> {
Angle(radians: lhs.radians - rhs.radians)
}

public static func -= (lhs: inout Angle<T>, rhs: Angle<T>) {
lhs.radians -= rhs.radians
}
}

public extension Angle {
static func * (lhs: Angle<T>, rhs: T) -> Angle<T> {
Angle(radians: lhs.radians * rhs)
}

static func *= (lhs: inout Angle<T>, rhs: T) {
lhs.radians *= rhs
}

static func * (lhs: T, rhs: Angle<T>) -> Angle<T> {
Angle(radians: rhs.radians * lhs)
}

static func / (lhs: Angle<T>, rhs: T) -> Angle<T> {
assert(rhs != 0)
return Angle(radians: lhs.radians / rhs)
}

static func /= (lhs: inout Angle<T>, rhs: T) {
assert(rhs != 0)
lhs.radians /= rhs
}
}

private func normalize<T>(_ input: T, limit: T) -> T
where T: Real {
var normalized = input

while normalized > limit {
normalized -= 2 * limit
}

while normalized < -limit {
normalized += 2 * limit
}

return normalized
}
140 changes: 140 additions & 0 deletions Tests/RealTests/AngleTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//===--- AngleTests.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import RealModule
import XCTest
import _TestSupport

internal extension Real
where Self: BinaryFloatingPoint {
static func conversionBetweenRadiansAndDegreesChecks() {
let angleFromRadians = Angle<Self>(radians: Self.pi / 3)
assertClose(60, angleFromRadians.degrees)

let angleFromDegrees = Angle<Self>(degrees: 120)
// the compiler complains with the following line
// assertClose(2 * Self.pi / 3, angleFromDegrees.radians)
assertClose(2 * Double(Self.pi) / 3, angleFromDegrees.radians)
}

static func trigonometricFunctionChecks() {
assertClose(1.1863995522992575361931268186727044683, Angle<Self>.acos(0.375).radians)
assertClose(0.3843967744956390830381948729670469737, Angle<Self>.asin(0.375).radians)
assertClose(0.3587706702705722203959200639264604997, Angle<Self>.atan(0.375).radians)
assertClose(0.54041950027058415544357836460859991, Angle<Self>.atan2(y: 0.375, x: 0.625).radians)

assertClose(0.9305076219123142911494767922295555080, cos(Angle<Self>(radians: 0.375)))
assertClose(0.3662725290860475613729093517162641571, sin(Angle<Self>(radians: 0.375)))
assertClose(0.3936265759256327582294137871012180981, tan(Angle<Self>(radians: 0.375)))
}

static func specialDegreesTrigonometricFunctionChecks() {
XCTAssertEqual(1, cos(Angle<Self>(degrees: -360)))
XCTAssertEqual(0, cos(Angle<Self>(degrees: -270)))
XCTAssertEqual(-1, cos(Angle<Self>(degrees: -180)))
assertClose(-0.86602540378443864676372317075293618347, cos(Angle<Self>(degrees: -150)))
assertClose(-0.70710678118654752440084436210484903929, cos(Angle<Self>(degrees: -135)))
assertClose(-0.5, cos(Angle<Self>(degrees: -120)))
XCTAssertEqual(0, cos(Angle<Self>(degrees: -90)))
assertClose(0.5, cos(Angle<Self>(degrees: -60)))
assertClose(0.70710678118654752440084436210484903929, cos(Angle<Self>(degrees: -45)))
assertClose(0.86602540378443864676372317075293618347, cos(Angle<Self>(degrees: -30)))
XCTAssertEqual(1, cos(Angle<Self>(degrees: 0)))
assertClose(0.86602540378443864676372317075293618347, cos(Angle<Self>(degrees: 30)))
assertClose(0.70710678118654752440084436210484903929, cos(Angle<Self>(degrees: 45)))
assertClose(0.5, cos(Angle<Self>(degrees: 60)))
XCTAssertEqual(0, cos(Angle<Self>(degrees: 90)))
assertClose(-0.5, cos(Angle<Self>(degrees: 120)))
assertClose(-0.70710678118654752440084436210484903929, cos(Angle<Self>(degrees: 135)))
assertClose(-0.86602540378443864676372317075293618347, cos(Angle<Self>(degrees: 150)))
XCTAssertEqual(-1, cos(Angle<Self>(degrees: 180)))
XCTAssertEqual(0, cos(Angle<Self>(degrees: 270)))
XCTAssertEqual(1, cos(Angle<Self>(degrees: 360)))

XCTAssertEqual(0, sin(Angle<Self>(degrees: -360)))
XCTAssertEqual(1, sin(Angle<Self>(degrees: -270)))
XCTAssertEqual(0, sin(Angle<Self>(degrees: -180)))
assertClose(-0.5, sin(Angle<Self>(degrees: -150)))
assertClose(-0.70710678118654752440084436210484903929, sin(Angle<Self>(degrees: -135)))
assertClose(-0.86602540378443864676372317075293618347, sin(Angle<Self>(degrees: -120)))
XCTAssertEqual(-1, sin(Angle<Self>(degrees: -90)))
assertClose(-0.86602540378443864676372317075293618347, sin(Angle<Self>(degrees: -60)))
assertClose(-0.70710678118654752440084436210484903929, sin(Angle<Self>(degrees: -45)))
assertClose(-0.5, sin(Angle<Self>(degrees: -30)))
XCTAssertEqual(0, sin(Angle<Self>(degrees: 0)))
assertClose(0.5, sin(Angle<Self>(degrees: 30)))
assertClose(0.70710678118654752440084436210484903929, sin(Angle<Self>(degrees: 45)))
assertClose(0.86602540378443864676372317075293618347, sin(Angle<Self>(degrees: 60)))
XCTAssertEqual(1, sin(Angle<Self>(degrees: 90)))
assertClose(0.86602540378443864676372317075293618347, sin(Angle<Self>(degrees: 120)))
assertClose(0.70710678118654752440084436210484903929, sin(Angle<Self>(degrees: 135)))
assertClose(0.5, sin(Angle<Self>(degrees: 150)))
XCTAssertEqual(0, sin(Angle<Self>(degrees: 180)))
XCTAssertEqual(-1, sin(Angle<Self>(degrees: 270)))
XCTAssertEqual(0, sin(Angle<Self>(degrees: 360)))

XCTAssertEqual(0, tan(Angle<Self>(degrees: -360)))
XCTAssertEqual(.infinity, tan(Angle<Self>(degrees: -270)))
XCTAssertEqual(0, tan(Angle<Self>(degrees: -180)))
assertClose(0.57735026918962576450914878050195745565, tan(Angle<Self>(degrees: -150)))
XCTAssertEqual(1, tan(Angle<Self>(degrees: -135)))
assertClose(1.7320508075688772935274463415058723669, tan(Angle<Self>(degrees: -120)))
XCTAssertEqual(-.infinity, tan(Angle<Self>(degrees: -90)))
assertClose(-1.7320508075688772935274463415058723669, tan(Angle<Self>(degrees: -60)))
XCTAssertEqual(-1, tan(Angle<Self>(degrees: -45)))
assertClose(-0.57735026918962576450914878050195745565, tan(Angle<Self>(degrees: -30)))
XCTAssertEqual(0, tan(Angle<Self>(degrees: 0)))
assertClose(0.57735026918962576450914878050195745565, tan(Angle<Self>(degrees: 30)))
XCTAssertEqual(1, tan(Angle<Self>(degrees: 45)))
assertClose(1.7320508075688772935274463415058723669, tan(Angle<Self>(degrees: 60)))
XCTAssertEqual(.infinity, tan(Angle<Self>(degrees: 90)))
assertClose(-1.7320508075688772935274463415058723669, tan(Angle<Self>(degrees: 120)))
XCTAssertEqual(-1, tan(Angle<Self>(degrees: 135)))
assertClose(-0.57735026918962576450914878050195745565, tan(Angle<Self>(degrees: 150)))
XCTAssertEqual(0, tan(Angle<Self>(degrees: 180)))
XCTAssertEqual(-.infinity, tan(Angle<Self>(degrees: 270)))
XCTAssertEqual(0, tan(Angle<Self>(degrees: 360)))

}
}

final class AngleTests: XCTestCase {
#if swift(>=5.3) && !(os(macOS) || os(iOS) && targetEnvironment(macCatalyst))
func testFloat16() {
if #available(iOS 14.0, watchOS 14.0, tvOS 7.0, *) {
Float16.conversionBetweenRadiansAndDegreesChecks()
Float16.trigonometricFunctionChecks()
Float16.specialDegreesTrigonometricFunctionChecks()
}
}
#endif

func testFloat() {
Float.conversionBetweenRadiansAndDegreesChecks()
Float.trigonometricFunctionChecks()
Float.specialDegreesTrigonometricFunctionChecks()
}

func testDouble() {
Double.conversionBetweenRadiansAndDegreesChecks()
Double.trigonometricFunctionChecks()
Double.specialDegreesTrigonometricFunctionChecks()
}

#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.conversionBetweenRadiansAndDegreesChecks()
Float80.trigonometricFunctionChecks()
Float80.specialDegreesTrigonometricFunctionChecks()
}
#endif
}
8 changes: 6 additions & 2 deletions Tests/RealTests/ElementaryFunctionChecks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ internal func assertClose<T>(
file: StaticString = #file,
line: UInt = #line
) -> T where T: BinaryFloatingPoint {
// we need to first check if the values are zero before we check the signs
// otherwise, "0" and "-0" compare as unequal (eg. sin(-180) == 0)
let expectedT = T(expected)
if observed.isZero && expectedT.isZero { return 0 }

// 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.
Expand All @@ -38,8 +43,7 @@ internal func assertClose<T>(
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
Expand Down