Skip to content

GageHoweTamu/decimal-fraction-approximator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Decimal -> Fraction Approximation

This algorithm finds the simplest fraction closest to a decimal. Eg. "approximate the value of pi with an error of less than 0.5%" (returns the fraction 22/7)

Accuracy is specified with "accuracy_score", the minimum fractional error between the input and the output fraction.

Rust refactor!

Now refactored in Rust and runs thousands of times faster.
"
Timer started
Starting approximation
Timer stopped
3.141592653589793 approximates to 3 + 244252/1725033, which equals 3.1415926535898153. This approximation is 99.99999999999929% accurate.
Time elapsed is: 7.26475ms
"

Compare this to Python, which took 11.82 seconds: ~1627 times slower.

Here is a graph of the average running time over the fractional error the algorithm was required to achieve. I suspect floating point error is responsible for the strange behavior over E-15; This can probably solved with Rust's BigDecimal eventually, but the proof of concept is good enough for now.

Screenshot 2023-12-26 at 9 36 22 PM

Python

Sample output given input_value = 3.1415926535897932384626433832795028841971, accuracy_score = 0.001):
"
numerator: 0
denominator: 2
numerator: 0
denominator: 3
...
numerator: 9
denominator: 64
Desired accuracy: 0.001 * 100%
End value: 3.140625
End accuracy: 1.0003081086057053
Approximation of 3.141592653589793: 3 + 9/64, or 201/64.
"

I'm currently writing a Dev.to article about this, should be done soon
https://dev.to/gagehowetamu/using-fractions-to-store-high-accuracy-float-values-23dm-temp-slug-830620?preview=b7b68f09c80f0b6ce967410162be98f55455dfc29c24e8d57ebd1098ea257686b3217f71bb3c9e8fd4b2bef50e9131cbb32d355fda40c85618bf9207

About

Approximate decimals with the closest fraction: With max error: 0.5%, pi -> 22/7 in ~37µs

Resources

Stars

Watchers

Forks

Releases

No releases published