Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/dagronf/dsfrational
- Owner: dagronf
- License: mit
- Created: 2020-01-05T01:07:05.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2020-01-05T01:31:24.000Z (almost 5 years ago)
- Last Synced: 2024-11-30T12:21:32.984Z (about 1 month ago)
- Topics: objective-c, rational, swift
- Language: Swift
- Homepage:
- Size: 4.88 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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
```swift
/// Swift examplelet 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 exampleid 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)