Numeric facilities for Swift

Related tags

Math swift math numerics
Overview

NumericAnnex
NumericAnnex

NumericAnnex supplements the numeric facilities provided in the Swift standard library.

Build Status codecov

Features

  • The exponentiation operator ** and the compound assignment operator **=.
  • Extension methods for BinaryInteger exponentiation, square root, cube root, greatest common divisor, and least common multiple.
  • Math, a protocol for signed numeric types that support elementary functions.
  • Real, a protocol for floating-point types that support elementary functions and a selection of special functions.
  • PRNG, a protocol for pseudo-random number generators.
  • Rational, a value type to represent rational values which supports division by zero.
  • Complex, a value type to represent complex values in Cartesian form.
  • Random and Random.Xoroshiro, two reference types implementing efficient pseudo-random number generators.

Note: This project is in the early stages of development and is not production-ready at this time.

Requirements

NumericAnnex requires Swift 4.1 (swift-4.1-branch) or Swift 4.2 (master). On Apple platforms, it also requires the Security framework for cryptographically secure random bytes.

Installation

After NumericAnnex has been cloned or downloaded locally, build the library using the command swift build (macOS) or swift build -Xcc -D_GNU_SOURCE (Linux). Run tests with the command swift test (macOS) or swift test -Xcc -D_GNU_SOURCE (Linux). An Xcode project can be generated with the command swift package generate-xcodeproj.

To add the package as a dependency using CocoaPods, insert the following line in your Podfile:

pod 'NumericAnnex', '~> 0.1.19'

Swift Package Manager can also be used to add the package as a dependency. See Swift documentation for details.

Basic Usage

import NumericAnnex

print(2 ** 3)
// Prints "8".

print(4.0 ** 5.0)
// Prints "1024.0".

print(Int.cbrt(8))
// Prints "2".

print(Double.cbrt(27.0))
// Prints "3.0".

var x: Ratio = 1 / 4
// Ratio is a type alias for Rational<Int>.

print(x.reciprocal())
// Prints "4".

x *= 8
print(x + x)
// Prints "4".

x = Ratio(Float.phi) // Golden ratio.
print(x)
// Prints "13573053/8388608".

var z: Complex64 = 42 * .i
// Complex64 is a type alias for Complex<Float>.

print(Complex.sqrt(z))
// Prints "4.58258 + 4.58258i".

z = .pi + .i * .log(2 - .sqrt(3))
print(Complex.cos(z).real)
// Prints "-2.0".

Documentation

All public protocols, types, and functions have been carefully documented in the code. See the formatted reference for details.

The project adheres to many design patterns found in the Swift standard library. For example, Math types provide methods such as cubeRoot() and tangent() just as FloatingPoint types provide methods such as squareRoot().

No free functions are declared in this library unless they overload existing ones in the Swift standard library. Instead, functions such as cbrt(_:) and tan(_:) are provided as static members. This avoids collisions with C standard library functions that you may wish to use. It also promotes clarity at the call site when the result of a complex operation differs from that of its real counterpart (e.g., Complex128.cbrt(-8) != -2).

Future Directions

  • Add more tests, including performance tests
  • Design and implement additional methods on PRNG

License

All original work is released under the MIT license. See LICENSE for details.

Portions of the complex square root and elementary transcendental functions use checks for special values adapted from libc++. Code in libc++ is dual-licensed under the MIT and UIUC/NCSA licenses.

Comments
  • Update generic algorithms for revised integer protocols [NFC]

    Update generic algorithms for revised integer protocols [NFC]

    This PR updates generic algorithms to match recent revisions to the standard library. The changes, specifically, are:

    • The initializer .init(extendingOrTruncating:) is now .init(truncatingIfNeeded:)
    • ArithmeticOverflow is abolished
    • Smart shifts and binary shifts are reorganized

    Some trivial changes to a doc comment are incidentally included in this PR.

    This PR will not pass CI testing until the next beta release of XCode and should not be merged until that time.

    opened by xwu 0
  • Update .travis.yml to enable multiplatform CI

    Update .travis.yml to enable multiplatform CI

    This PR modifies the Travis CI configuration file to set up testing on macOS (in addition to Linux).

    The macOS job uses xcodebuild to test the Xcode project generated by the Swift Package Manager.

    opened by xwu 0
  • Expand testing

    Expand testing

    This PR adds tests for BinaryInteger.pow and for default implementations in Math and Real. In addition:

    • The default implementation of cubeRoot is corrected and removed from Math to Real.
    • A correction is made for an error in the default implementation of Math.phi.
    • Special values are now handled in the default implementation of Real.hypot.

    This PR also includes an incidental simplification of some operator implementations in Complex, which will simplify later testing.

    opened by xwu 0
  • Add PRNG and Random

    Add PRNG and Random

    This PR introduces a protocol named PRNG for pseudo-random number generators, which is class-constrained and refines IteratorProtocol and Sequence. Extension methods on PRNG should not be susceptible to "modulo bias" problems that can occur when Element.max - Element.min + 1 is not a power of two.

    It also introduces a (final) class named Random, which conforms to PRNG and implements the xorshift128+ algorithm, and another (final) class named Random.Xoroshiro, which conforms to PRNG and implements the xoroshiro128+ algorithm. Much work remains to be done, including testing the code using TestU01.

    enhancement 
    opened by xwu 0
  • Add partial implementation of arbitrary-precision integers

    Add partial implementation of arbitrary-precision integers

    ...and correct some implementations in Rational.

    Although it was possible to implement many of the simpler algorithms using a two's complement representation, it proved to be difficult to implement multiplication or division without taking the absolute value. Some reading suggests that most (if not all) arbitrary-precision integer implementations use sign-and-magnitude representation. Thus, I have switched back to that representation (which was one option that I had already explored).

    This PR contains working implementations of comparison, addition, subtraction, long multiplication, and negation. Additional testing is required to verify correctness.

    No attempt has yet been made to implement division or bit shifting, and no updated implementation is included for other bitwise operations. It remains unclear to me whether generic use of such operations always assumes two's complement representation, or whether it is appropriate to simply perform these bitwise operations on the native sign-and-magnitude representation.

    Future directions include implementation of more sophisticated multiplication algorithms such as Karatsuba.

    enhancement 
    opened by xwu 0
  • Add Rational type and integer protocol conformances

    Add Rational type and integer protocol conformances

    Work in progress to add a Rational type.

    Detailed design

    • To create a new Rational instance, the intended spelling for general use is let i: Rational<Int> = 3 / 4, which will always reduce the numerator and denominator to lowest terms. However, it is possible to construct a Rational instance with an unreduced numerator and denominator through Rational.init(numerator:denominator:).

    • Arithmetic operations with canonical (i.e., reduced) fractions are guaranteed to return canonical fractions; arithmetic operations with unreduced fractions are guaranteed to return correct answers equal to--but not necessarily in--their canonical form.

    • Comparison never overflows. Multiplication will overflow only if the final result is not representable as a value of type Rational<T>. However, at present, addition may overflow even if the final result is representable as a value of type Rational<T> if intermediate computational steps require numerators or denominators not representable as values of type T.

    • For simplicity, Rational is limited to numerators and denominators which are of a type that conform to SignedInteger. Therefore, Rational<T>.Magnitude must be Rational<T> and not Rational<T.Magnitude>. The implication is that we must prohibit T.min / 1 from being a value of type Rational<T>, since its magnitude is not representable as a Rational<T>.Magnitude.

    Even without the Rational.Magnitude requirement, representing 1 / T.min would be problematic: the sign is stored in the numerator when the fraction is canonicalized, but -1 / -T.min cannot be represented as a Rational<T>.

    Outstanding issues

    An optimal implementation of Rational.+ would make use of full-width multiplication and division, which is not yet implemented in the standard library.

    enhancement 
    opened by xwu 0
Releases(0.1.19)
  • 0.1.19(Aug 28, 2017)

  • 0.1.18(Aug 27, 2017)

  • 0.1.17(Aug 19, 2017)

  • 0.1.16(Aug 19, 2017)

  • 0.1.15(Aug 19, 2017)

  • 0.1.14(Jul 16, 2017)

    • Removed Complex.isCanonical and Complex.polar.
    • Fixed implementation of Complex.isNaN and Complex.isSignalingNaN to align with C/C++ standards: a complex value is NaN if at least one of its components is NaN and the other is not infinite.
    • Fixed implementation of Complex multiplication and division to align handling of special values with C/C++ standards.
    • Fixed implementation of Complex.tanh(_:) to align handling of special values with C/C++ standards.
    • Refined implementation of Complex.description for values with a negative imaginary component.
    • Fixed implementation of Rational initializers that convert from a BinaryFloatingPoint value.
    Source code(tar.gz)
    Source code(zip)
  • 0.1.13(Jul 4, 2017)

  • 0.1.12(Jun 14, 2017)

    • Added integer square root and cube root functions.
    • Removed power(of:) requirement from Math, substituting pow(_:_:) (formerly an extension method).
    Source code(tar.gz)
    Source code(zip)
  • 0.1.11(Jun 13, 2017)

  • 0.1.10(Jun 12, 2017)

  • 0.1.9(Jun 10, 2017)

    • Renamed FloatingPointMath to Real.
    • Updated implementation of Complex.hyperbolicTangent to align handling of special values to revised C standard.
    • Updated swift-tools-version to 4.0.
    Source code(tar.gz)
    Source code(zip)
  • 0.1.8(Jun 4, 2017)

    • Removed initializer requirements from FloatingPointMath, moving functionality to an extension to BinaryFloatingPoint.
    • Reorganized code and edited comments to improve documentation.
    Source code(tar.gz)
    Source code(zip)
  • 0.1.7(Jun 3, 2017)

    • Added initial implementation of a pseudo-random number generator protocol and conforming types.
    • Restored constraints on FloatingPointMath to refine FloatingPoint and not BinaryFloatingPoint.
    Source code(tar.gz)
    Source code(zip)
  • 0.1.6(May 12, 2017)

  • 0.1.5(May 7, 2017)

  • 0.1.4(Apr 30, 2017)

  • 0.1.3(Apr 24, 2017)

  • 0.1.2(Apr 24, 2017)

Owner
Xiaodi Wu
Xiaodi Wu
A collection of functions for statistical calculation written in Swift.

σ (sigma) - statistics library written in Swift This library is a collection of functions that perform statistical calculations in Swift. It can be us

Evgenii Neumerzhitckii 658 Jan 5, 2023
Multi-dimensional Swift math

Upsurge Upsurge implements multi-dimensional data structures and operations. It brings numpy-like operations to Swift. Upsurge no longer supports DSP

Alejandro Isaza 180 Dec 20, 2022
Swift Matrix Library

Swift Matrix and Machine Learning Library Note: tensorflow/swift and apple/swift-numerics/issues/6 have or will have more complete support for NumPy-l

Scott Sievert 591 Sep 5, 2022
Overload +-*/ operator for Swift, make it easier to use (and not so strict)

Easy-Cal-Swift Overview This file is an overloading of +-*/ operator for Swift, to make it easier to use (and not so strict) It can make your life wit

Wei Wang 272 Jun 29, 2022
Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

Matft Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy. Matft Feature & Usage Declaration MfArray MfType Subscription

null 80 Dec 21, 2022
Swift Custom Operators for Mathematical Notation

Euler Euler uses custom operators in the "Math Symbols" character set to implement functions using traditional mathematical notation. Please keep in m

Mattt 1.1k Jan 4, 2023
SwiftMath is a Swift framework providing some useful math constructs and functions

SwiftMath is a Swift framework providing some useful math constructs and functions, like complex numbers, vectors, matrices, quaternions, and polynomials.

Matteo Battaglio 175 Dec 2, 2022
VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions

Purpose VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based g

Nick Lockwood 341 Dec 31, 2022
A cross-platform Swift library for evaluating mathematical expressions at runtime

Introduction What? Why? How? Usage Installation Integration Symbols Variables Operators Functions Arrays Performance Caching Optimization Standard Lib

Nick Lockwood 738 Jan 7, 2023
Math expression parser built with Point•Free's swift-parsing package

swift-math-parser Basic math expression parser built with Point•Free's swift-parsing package. NOTE: currently, this uses a fork of that fixes a parsin

Brad Howes 36 Dec 14, 2022
Swift Matrix Library

Swift Matrix and Machine Learning Library Note: tensorflow/swift and apple/swift-numerics/issues/6 have or will have more complete support for NumPy-l

Scott Sievert 591 Sep 5, 2022
MRFoundation - A library to complement the Swift Standard Library

MRFoundation MRFoundation is a library to complement the Swift Standard Library.

Roman Mogutnov 2 Feb 12, 2022
Numerals is a package containing additional numeric types for the Swift programming language.

swift-numerals Numerals is a package containing additional numeric types for the Swift programming language. Contents The package currently provides t

Alexandre H. Saad 0 Jul 28, 2022
Convert numeric addresses to symbols with callStackSymbols and dSYM.

Symbolicator Convert numeric addresses to symbols with callStackSymbols and dSYM files. Installation Supports Swift Package Manager.

Naruki Chigira 6 Sep 16, 2022
Animate numeric value while setting new value to label

NumericAnimatedLabel Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installati

Javal Nanda 28 Oct 11, 2021
SwiftyKeyboard: a full customized numeric keyboard for iOS

SwiftyKeyboard Overview SwiftyKeyboard is an iOS customized enhanced keyboard. T

SwiftyKit 2 Jun 30, 2022
A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift

A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift. It features a great API and a battle-tested core. Supporting both MongoDB in server and embedded environments.

null 646 Dec 10, 2022
Swift-music - swift-music is a swift package that provides an easy-to-use API for music related developments.

?? swift-music Introduction swift-music is a swift package that provides an easy-to-use API for music related developments. Currently available module

Jin Zhang 4 Feb 8, 2022
Swift-extensions - Swift package extending the Swift programming language.

swift-extensions A package containing extensions for the Swift programming language. Contribution Reporting a bug If you find a bug, please open a bug

Alexandre H. Saad 2 Jun 12, 2022
BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Blockchain Commons, LLC — A “not-for-profit” benefit corporation 4 Oct 6, 2022