Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/dagronf/dsfrational

A Swift extension for floating point values to return rational components
https://github.com/dagronf/dsfrational

objective-c rational swift

Last synced: 17 days ago
JSON representation

A Swift extension for floating point values to return rational components

Awesome Lists containing this project

README

        

# Objective-C/Swift Rational class

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









CocoaPods

Swift Package Manager

```swift
/// 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
/// Objective-C example

id 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](https://www.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](https://www.gamedev.net/forums/topic/354209-how-do-i-convert-a-decimal-to-a-fraction-in-c/?do=findComment&comment=3321651)