DSFRational

master

A Swift extension for floating point values to return rational components
dagronf/DSFRational

Objective-C/Swift Rational class

An extension for floating point values to return the rational components for that value

CocoaPods Swift Package Manager

/// Swift example

let rational = -9.90.rationalValue
// result.fraction, -9.90)
// result.description, "-9 9/10")
// result.whole, -9)
// result.numerator, 9)
// result.denominator, 10)
/// Objective-C example

id<RationalRepresentation> result = [DSFRational valueFor:-11.112];
assert([[result description] isEqual:@"-11 14/125"]);
assert([result whole] == -11);
assert([result numerator] == 14);
assert([result denominator] == 125);
assert([result fraction] == -11.112);

Notes

The algorithm arises from a comment on GameDev.net by user John Bolton.

Here is an algorithm for converting a value to the closest fraction (given a maximum value for the denominator). It is based on Farey Sequences. It is probably much faster than finding GCDs and the results are much more useful. For example, using the suggestions above, .333333 will be converted to 333333/1000000, which is probably not what you want. Using this algorithm, you will get 1/3.

Click here to see original post

Description

  • Swift Tools 5.1.0
View More Packages from this Author

Dependencies

  • None
Last updated: Mon Mar 18 2024 19:26:56 GMT-0900 (Hawaii-Aleutian Daylight Time)