2

Do you know how to make a rational approximation of a decimal number in C (similar to rat Matlab function)?

Update

If we want a P/Q approximation of a double number number, a quick fix could be:

int factor=1000000;
P=floor(number*factor);
Q=factor;

The error is less than (number/factor), which is negligible.

Luis Andrés García
  • 5,852
  • 10
  • 43
  • 57

2 Answers2

3

Continued fractions can be used to calculate rational approximations to real numbers that are optimal in a sense. That way with the input 0.33333333 you have a chance of obtaining 1/3 rather than 3333/10000.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

You can do the same as you have done in your update, but then check for the highest common factor between the top and bottom and simplify. For example, 0.5 would go to 500000/1000000 doing it your method. They share a common factor of 500000 so you can divide both top and bottom by that to get 1/2. Google has a lot of examples of hcf functions , such as this one (Edit: And this impressive list).

Matt
  • 7,100
  • 3
  • 28
  • 58