# Fractions

• March 7th, 2010, 07:35 AM
debug
Fractions
is there any standard library function to convert decimals to fractions, for example if the input is 3.14159265 the output = 22/7 ?
thanks!
• March 8th, 2010, 11:29 PM
helloworld922
Re: Fractions
Unfortunately, no. You can create a naive fraction class fairly easily, though. See Wikipedia - Repeating Decimals for a simple method to calculate the numerator and denominator given a decimal. Note that you will run into several problems:

1. Floating point numbers can also be used to hold approximations of irrational numbers (such as pi or sqrt(2)), and these have no fraction equivalent. 22/7 = 3.1428571428571 :P (bold part is where Pi and 22/7 deviate)

2. Floating point numbers are restricted in the precision that they can hold. Thus, even though 0.3333333... = 1/3, the floating point representation would be 0.3333333333333333 = 3333333333333333/10000000000000000. It is possible to check for some common fractions such as 1/3, but even so, the floating point arithmetic might truncate some digits differently as you perform operations, leaving something like 0.3333333333333342 (or even greater error depending on the application), which would be much more difficult to determine a fraction equivalent.

3. Integers/longs are limited to a certain maximum value. In the above example, longs were more than capable of storing both number representations. However, say you had the number 6.02214179e23 (a very useful number). A long would be unable to store the numerator for that number, even though the denominator would be 1.

There is a way to try and get around problem 3 using BigInteger, and using BigDecimal on 2 would help somewhat, but ultimately you will have the same problems when you try to compute the fraction equivalent of certain numbers (ex. 1/3 using a BigDecimal will still truncate the number of 3's you will have, but will just do so later).