CFraction class is a handy class when dealing with
doubles and fractions. You can use it like a
double and do anything you would do with a
double, plus you assign strings to it. When you need to get a string representation, use one of the methods returning a
CString. Or, if you do not use
CString, there are methods for
F1 = 5.126;
F2 = "5.126";
F1 = "5 63/500";
D = F1;
F2 = D;
F1 = F2 + D;
F2 = F1/D;
if ((F1 > D) || (F1 < F2))
D = F2/F1;
F2 = 15.0135;
S = F2.ToString();
S = F2.ToString(64);
S = F2.ToStockString();
S = F2.ForceToStockString();
S = F2.ForceToStockString(64);
F1 = 3.1415926535897932384626433832795;
S = F1.ToString();
S = F1.ToString(10.0e-50);
S = F1.ToString(999);
The algorithm was developed using the formula for converting a decimal fraction to a string fraction. Any fractional part can be represented as:
1/(I1 + 1/(I2 + 1/(I3 + 1/In ...
where I1 is the integer part of the reciprocal of the fraction and I2 is the integer part of the reciprocal minus I1 ... etc. To determine the integer numerator and denominator, the expression can be reduced. It turns out that the numerator is simpler to calculate than the denominator, so the denominator can simply be determined by dividing the numerator by the original decimal.
Reduction of 1/(I1 + 1/(I2 + 1/(I3 + 1/In ... ))) - There is a way to mathematically reduce this elegantly. However, I think a simple step by step algebraic approach will be understood by more readers.
- 1 I term: 1/I1 Numerator N1 = 1
- 2 I terms: 1/(I1 + 1/I2) Multiply by I2/I2 = I2/((I1*I2) + 1),
Numerator N2 = I2
- 3 I terms: 1/(I1 + 1/(I2 + 1/I3)) Multiply by I3/I3 = 1/(I1 + I3/(I2*I3) + 1)
then Multiply by ((I2*I3) + 1)/((I2*I3) + 1) = ((I2*I3) + 1)/(I1*((I2*I3) + 1) + I3),
Numerator N3 = ((I2*I3) + 1)
- 4 I terms: ...
Multiply by I4/I4 = 1/(I1 + 1/(I2 + I4/(I3*I4) + 1))
Multiply by (I3*I4) + 1) = 1/(I1 + ((I3*I4) + 1)/(I2*((I3*I4) + 1) + I4)).. ,
Numerator N4 = I2*((I3*I4) + 1) + I4
As we continue, a pattern to the numerators appears showing that N1 = 1, N2 = I2, and Nn = In*Nn-2 + Nn-3 .
This is fairly simple to code.