## Introduction

The `CFraction`

class is a handy class when dealing with `double`

s 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 `char *`

.

## Example usage:

CFraction F1,F2;
double D;
CString S;
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/(I_{1} + 1/(I_{2} + 1/(I_{3} + 1/I_{n} ...

where I_{1} is the integer part of the reciprocal of the fraction and I_{2} is the integer part of the reciprocal minus I_{1} ... 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/(I_{1} + 1/(I_{2} + 1/(I_{3} + 1/I_{n} ... ))) - 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/I
_{1} Numerator N_{1} = 1
- 2 I terms: 1/(I
_{1} + 1/I_{2}) Multiply by I_{2}/I_{2} = I_{2}/((I_{1}*I_{2}) + 1),
Numerator N_{2} = I_{2}

- 3 I terms: 1/(I
_{1} + 1/(I_{2} + 1/I_{3})) Multiply by I_{3}/I_{3} = 1/(I_{1} + I_{3}/(I_{2}*I_{3}) + 1)
then Multiply by ((I_{2}*I_{3}) + 1)/((I_{2}*I_{3}) + 1) = ((I_{2}*I_{3}) + 1)/(I_{1}*((I_{2}*I_{3}) + 1) + I_{3}),

Numerator N_{3} = ((I_{2}*I_{3}) + 1)

- 4 I terms: ...
Multiply by I_{4}/I_{4} = 1/(I_{1} + 1/(I_{2} + I_{4}/(I_{3}*I_{4}) + 1))

Multiply by (I_{3}*I_{4}) + 1) = 1/(I_{1} + ((I_{3}*I_{4}) + 1)/(I_{2}*((I_{3}*I_{4}) + 1) + I_{4})).. ,

Numerator N_{4} = I_{2}*((I_{3}*I_{4}) + 1) + I_{4}

As we continue, a pattern to the numerators appears showing that N_{1} = 1, N_{2} = I_{2}, and N_{n} = I_{n}*N_{n-2} + N_{n-3} .

This is fairly simple to code.