Reputation: 899
I've wrote a method for polynomial long division. And it works perfect with "good" polynomials. Under "good" I mean coefficients that divides accurate. Today I've faced with issue when tried to divide 2*x^3-18*x^2+.... / 7.00000(much zeros)0000028*x^2 + 5*x + ..
. After division 2*x^3 / 7.000...000028*x^2
I got 0.285714....53*x
. On next step we need to multiply 0.2857....53*x
on 7.00000...0000028*x^2 + 5*x + ..
and subtract it from dividend polynomial 2*x^3-18*x^2+...
and get new polynomial with degree = 2. But because of problem with double
type I actually got polynomial 2.220....E-16*x^3 - 6*x^2 + ...
. I know that it is in fact zero near the x^3
. I do not want to invent smth new and strange, that is why I am asking how to resolve it beautifully and correctly. Thanks.
Upvotes: 0
Views: 64
Reputation: 26185
Many division results such as 1/7 cannot be represented exactly in either double or BigDecimal. If you go with BigDecimal you would have to pick a number of digits to preserve, and deal with rounding error. For double, you get more convenient arithmetic, but a fixed number of significant bits.
You have two options.
One is to handle rounding error. When a result is very close to zero, so close that it is probably due to rounding error, treat it as zero. I don't know whether that will work for your algorithm or not. If you go this way, you can use either double or BigDecimal.
The second option is to use a rational number package. In rational number arithmetic all division results can be represented exactly. 1/7 remains 1/7, without being rounded to a terminating decimal or binary fraction. If you go this way, search for "java rational number" (no quotes) and decide which one you like best.
Upvotes: 2