Skip to content

Introducing Angle type [Issue #88] #169

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 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
205 changes: 205 additions & 0 deletions Sources/RealModule/Angle.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
//===--- 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>: Equatable {
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) }
}

extension ElementaryFunctions
where Self: Real {
/// See also:
/// -
/// `ElementaryFunctions.cos()`
public 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()`
public 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()`
public 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
}
}

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

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

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

/// See also:
/// -
/// `RealFunctions.atan2()`
public 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
}
}

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

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

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

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

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

extension Angle {
/// Checks whether the current angle is contained within a given closed range.
///
/// - Parameters:
///
/// - range: The closed angular range within which containment is checked.
public func contained(in range: ClosedRange<Angle<T>>) -> Bool {
range.contains(self)
}

/// Checks whether the current angle is contained within a given half-open range.
///
/// - Parameters:
///
/// - range: The half-open angular range within which containment is checked.
public func contained(in range: Range<Angle<T>>) -> Bool {
range.contains(self)
}
}

extension Angle: Comparable {
public static func < (lhs: Angle<T>, rhs: Angle<T>) -> Bool {
guard lhs != rhs else {
return false
}
return lhs.radians < rhs.radians
}
}

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
}
176 changes: 176 additions & 0 deletions Tests/RealTests/AngleTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
//===--- 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)))
}

static func additiveArithmeticTests() {
var angle = Angle(degrees: 30)
assertClose(50, (angle + Angle(degrees: 20)).degrees)
assertClose(10, (angle - Angle(degrees: 20)).degrees)
XCTAssertEqual(Angle(degrees: 60), angle * 2)
XCTAssertEqual(Angle(degrees: 60), 2 * angle)
XCTAssertEqual(Angle(degrees: 15), angle / 2)
angle += Angle(degrees: 10)
XCTAssertEqual(Angle(degrees: 40), angle)
angle -= Angle(degrees: 20)
XCTAssertEqual(Angle(degrees: 20), angle)
angle *= 3
XCTAssertEqual(Angle(degrees: 60), angle)
angle /= 6
XCTAssertEqual(Angle(degrees: 10), angle)
}

static func rangeContainmentTests() {
let angle = Angle(degrees: 30)
XCTAssertTrue(angle.contained(in: Angle(degrees: 10)...Angle(degrees: 40)))
XCTAssertTrue(angle.contained(in: Angle(degrees: 10)...Angle(degrees: 30)))
XCTAssertTrue(angle.contained(in: Angle(degrees: 30)...Angle(degrees: 40)))
XCTAssertFalse(angle.contained(in: Angle(degrees: 10)...Angle(degrees: 20)))
XCTAssertFalse(angle.contained(in: Angle(degrees: 50)...Angle(degrees: 60)))
XCTAssertTrue(angle.contained(in: Angle(degrees: 30)..<Angle(degrees: 40)))
XCTAssertFalse(angle.contained(in: Angle(degrees: 10)..<Angle(degrees: 30)))
XCTAssertTrue(angle.contained(in: Angle(degrees: 10)..<Angle(degrees: 40)))
}
}

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()
Float16.additiveArithmeticTests()
Float16.rangeContainmentTests()
}
}
#endif

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

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

#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.conversionBetweenRadiansAndDegreesChecks()
Float80.trigonometricFunctionChecks()
Float80.specialDegreesTrigonometricFunctionChecks()
Float80.additiveArithmeticTests()
Float80.rangeContainmentTests()
}
#endif
}
Loading