In article <gekc6m$2n5$>, Lew <> wrote:
> Ramon wrote:
> > Yes I know that the mother of all problems is the CPU's floating point
> > numerical system. But is there a way how one can add -0.7 with 0.2 and
> > the answer is exactly -0.5?
>
> In decimal arithmetic accurate to, say, 6 places, is there a way to add 1/3
> and 1/7 so the answer is exactly 10/21?
An excellent rhetorical question, as it suggests rational arithmetic as
one approach to the OP's problem:
<http://jscience.org/api/org/jscience/mathematics/number/Rational.html>
<code>
import org.jscience.mathematics.number.Rational;
public class RationalTest {
public static void main(String[] args) {
Rational a = Rational.valueOf(-7, 10);
Rational b = Rational.valueOf(2, 10);
Rational sum = a.plus(b);
System.out.println(sum);
System.out.println(sum.doubleValue());
a = Rational.valueOf(1, 3);
b = Rational.valueOf(1, 7);
sum = a.plus(b);
System.out.println(sum);
System.out.println(sum.doubleValue());
}
}
</code>
<console>
-1/2
-0.5
10/21
0.47619047619047616
<.console>
--
John B. Matthews
trashgod at gmail dot com
http://home.roadrunner.com/~jbmatthews/