So for a project I am working on. I need to take a string representation of a floating point number, lets say "1.5" and do arithmetic on it with another floating point number. The catch is I cannot use floats to do this, since it specifically says in the requirements for my homework that I can't do this. How I am supposed to do something like add or subtract these numbers is break the string apart into it's characteristic (1) and it's mantissa(5). so in the program, the program will be represented as 1/2. However, if I wanted to add 1.5 with 1.3, 1/3 goes on forever. Thus making it impossible to convert 1/3 to 1/(some power of 10) and figure out how to add everything together. Is there an algorithm that can deal with cases of division like 1/3?

  • $\begingroup$ You have to convert the number to decimal representation or you have to use string explicitly? You can always use integers or treat "1/3+1/5" as the input. So what is the exact task? $\endgroup$ – Evil Sep 25 '17 at 0:13

You should implement rational numbers yourself. Store number as two integers. Use the greatest common divisor to factor out superflous representation. Literally write school algorithms for rational numbers - find common denominator for addition and then normalize number. At the end convert it to decimal representation with fixed precision. Namely use symbolic calculation as long as you can.

From your example:
$\frac{1}{3} + \frac{1}{5} = \frac{5}{15} + \frac{3}{15} = \frac{8}{15} \approx 0.5333$

If your task really requires to convert it to string at the first step, then you have to assume some precision, e.g. four numbers in decimal expansion, and then write your own code to operate on numbers. The exact decimal expansion is not always possible, as you have already realized, so $\frac{1}{3}$ would expand to "0.3333" (arbitrary length from my example. It may seem weird at first, but the floats are also inexact, with precision given by fixed length representation (e.g. 64, 80, 128 bits).

$\frac{1}{3} \approx 0.333; \frac{1}{5} \approx 0.2000$
$0.3333 + 0.2000 = 0.5333$
It gives the same approximate result.

| cite | improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.