num-rational icon indicating copy to clipboard operation
num-rational copied to clipboard

Feature request: Limiting precision

Open ijustlovemath opened this issue 3 years ago • 2 comments

I'm using this library to losslessly model orbits in an n-body simulator, and I've noticed that after just a few iterations, the length of the data field seems to be growing quite rapidly; quadratically or exponentially is my guess. It would be useful to be able to do something like:

let mut n = Ratio::from_float(1.0).unwrap();
n.max_precision(20); // maximum number of digits in either numerator or denominator is now 20, lossy approximations afterwards

You could implement this using Farey fractions, see here: https://math.stackexchange.com/questions/2438510/can-i-find-the-closest-rational-to-any-given-real-if-i-assume-that-the-denomina

I may also just be unfamiliar with the API and don't see where this option exists

ijustlovemath avatar Aug 12 '21 11:08 ijustlovemath

One workaround, which may be somewhat wasteful, is the following:

let mut x = Ratio::from_float(1.1).unwrap();
// do something to update x...
x = Ratio::from_float(x.to_f64().unwrap()).unwrap();

ijustlovemath avatar Aug 12 '21 15:08 ijustlovemath

I think it would be difficult to carry around a precision and maintain that throughout internal computation -- but it might not be so bad to offer some kind of "approximation" method to do this manually.

cuviper avatar Aug 23 '21 22:08 cuviper