Search code examples
cmatlabrational-numbers

Matlab rat function in C language


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.


Solution

  • 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.