We have a very data intensive system. It stores raw data, then computes percentages based on the number of correct responses / total trials.
Recently we have had customers who want to import old data into our system.
I need a way to covert a percentage to the nearest fraction.
Examples.
- 33% needs to give me 2/6. EVEN though 1/3 is .33333333
- 67% needs to give me 4/6. EVEN though 4/6 is .6666667
I realize I could just compute that to be 67/100, but that means i'd have to add 100 data points to the system when 6 would suffice.
Does anyone have any ideas?
EDIT Denominator could be anything. They are giving me a raw, rounded percentage and i'm trying to get as close to it with RAW data as possible
Answering my own question here. Would this work?
This will keep my denominator below 10.
Would it have to return 2/6 rather than 1/3? If its always in 6ths, then
Your requirements are contradicting: On the one hand, you want to "convert a percentage to the nearest fraction" (*), but on the other hand, you want fractions with small(est) numbers. You need to find some compromise when/how to drop precision in favor of smaller numbers. Your problem as it stands is not solvable.
(*) The nearest fraction f for any given (integer) percentage n is n/100. Per definition.
I have tried to satisfy your requirement by using continued fractions. By limiting the depth to three I got a reasonable approximation.
I failed to come up with an iterative (or recursive) approach in resonable time. Nevertheless I have cleaned it up a little. (I know that 3 letter variable names are not good but I can't think of good names for them :-/ )
The code gives you the best rational approximation within the specified tolerance it can find. The resulting fraction is reduced and is the best approximation among all fractions with the same or lower denominator.