swift-rational

1.0.1

Swift package for working with rational numbers
abdel-17/swift-rational

What's New

1.0.1

2024-01-15T23:13:50Z

fix: #3 limitDenominator traps due to negative denominator

Swift Rational

Introduction

Swift Rational provides the RationalModule module for working with rational numbers in Swift.

import RationalModule

let half = Rational<Int>(1, 2)

RationalModule has only a single dependency, swift-numerics.

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:
.package(url: "https://github.com/abdel-17/swift-rational", from: "1.0.0")
  1. Add RationalModule as a dependency for your target:
.target(
	name: "TargetName",
	dependencies: [
		.product(name: "RationalModule", package: "swift-rational")
	]
)
  1. 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.

let half = Rational(2, 4)
print(x.numerator)	// 1
print(x.denominator)	// 2

You can also use the integer initializer.

let one = Rational(1)

Or simply an integer literal.

let two: Rational<Int> = 2

Rational supports the standard arithmetic and comparison operators.

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 module.

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

Last updated: Mon Dec 02 2024 00:13:15 GMT-1000 (Hawaii-Aleutian Standard Time)