Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/abdel-17/swift-rational
Swift package for working with rational numbers
https://github.com/abdel-17/swift-rational
fractions math rational-numbers swift swift-package
Last synced: 11 days ago
JSON representation
Swift package for working with rational numbers
- Host: GitHub
- URL: https://github.com/abdel-17/swift-rational
- Owner: abdel-17
- License: mit
- Created: 2024-01-09T01:51:58.000Z (12 months ago)
- Default Branch: master
- Last Pushed: 2024-01-15T23:11:29.000Z (12 months ago)
- Last Synced: 2024-12-23T22:30:23.212Z (12 days ago)
- Topics: fractions, math, rational-numbers, swift, swift-package
- Language: Swift
- Homepage:
- Size: 66.4 KB
- Stars: 4
- Watchers: 1
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Swift Rational
## Introduction
Swift Rational provides the `RationalModule` module for working with rational numbers in Swift.
```swift
import RationalModulelet half = Rational(1, 2)
````RationalModule` has only a single dependency, [swift-numerics](https://github.com/apple/swift-numerics/tree/main).
## Using Swift Rational in your project
To use Swift Rational in a SwiftPM project:
1. Add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/abdel-17/swift-rational", from: "1.0.0")
```2. Add `RationalModule` as a dependency for your target:
```swift
.target(
name: "TargetName",
dependencies: [
.product(name: "RationalModule", package: "swift-rational")
]
)
```3. Add `import RationalModule` in your source code.
## API
`RationalModule` exports the `Rational` struct. It conforms to standard Swift protocols like `AdditiveArithmetic`, `Numeric`, `Hashable`, `Comparable`, and more.
You can create a `Rational` value using the fraction initializer.
```swift
let half = Rational(2, 4)
print(x.numerator) // 1
print(x.denominator) // 2
```You can also use the integer initializer.
```swift
let one = Rational(1)
```Or simply an integer literal.
```swift
let two: Rational = 2
````Rational` supports the standard arithmetic and comparison operators.
```swift
Rational(1, 2) + Rational(1, 4) // Rational(3, 4)
Rational(1) - Rational(1, 2) // Rational(1, 2)
Rational(2) * Rational(3, 4) // Rational(3, 2)
Rational(1) / Rational(1, 2) // Rational(2, 1)
Rational(1, 2) < Rational(3, 4) // true
```## Attributions
A lot of the implementations were ported over to Swift from Python's [fractions](https://github.com/python/cpython/blob/main/Lib/fractions.py) module.