1
$\begingroup$

I am currently using rational numbers to express currency and math operations with currency, while dealing with rational numbers has provided a great convenience in over coming the limitations of scaling integers into unit64 I have a few concerns around decimal fractions vs rational numbers and the quotient they express:

Given the following rational number:

$5764607523034235/576460752303423488$

this supposedly represents 0.01 'exactly', according to the 'quotToFloat' method found here: http://golang.org/src/pkg/math/big/rat.go

but given the following decimal fraction:

$1/100$

this supposedly does not represent 0.01 'exactly'.

My concern lies in holding 2 different rational numbers that represent the same qoutient but not being able to find equality between them without converting them and comparing.

Why is it that $1/100$ does not express 0.01 exactly? Am I butting up against base2 limitations?

$\endgroup$
3
  • $\begingroup$ If you want a computer to work with rational numbers and do the job in an exact manner, then you are likely better off using some library facility constructed for the express purpose of working with fractions (or make your own). Floats are not your friend in that case and will only lead to headaches. $\endgroup$
    – Arthur
    May 8, 2014 at 20:39
  • 1
    $\begingroup$ $576460752303423488 = 2^{59}$ and your observation reflects the fact that IEEE floats are indeed always fractions with powers of two in the denominator. Comparing $\frac ab$ with $\frac cd$ should be done by integer artihmetic: Check the sign of $ad-bc$ (assuming $b,d>0$ and no overflow occurs) $\endgroup$ May 8, 2014 at 20:45
  • $\begingroup$ @Arthur, the library I am using is explicitly designed to work with rational numbers, currently the only time I require to use a float is to check for equality between 2 fractions (which I don't believe should be necessary given a good GCD) $\endgroup$
    – Adrian
    May 8, 2014 at 20:46

1 Answer 1

0
$\begingroup$

Yes, you are up against base 2 limitations. It is the same as in base 10, you cannot represent $\frac 13=0.\overline 3$ exactly because it has a prime factor that does not divide $10$. $0.1_{10}=0.00011\overline{0011}_2$. It is a repeating "decimal" because of the factor $5$ in the denominator. Why are you using quotToFloat? It looks like your package has exact rationals, so you can just subtract them and check whether the difference is zero for equality.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .