Comparing a double against zero

前端 未结 4 2029
抹茶落季
抹茶落季 2020-12-15 19:50

I\'m new to Java and I\'ve been trying to implement an algorithm for finding the roots of a cubical equation. The problem arises when I calculate the discriminant and try to

4条回答
  •  生来不讨喜
    2020-12-15 20:35

    Here's solution that is precise when the input values are integers, though it is probably not the most practical.

    It will probably also work fine on input values that have a finite binary representation (eg. 0.125 does, but 0.1 doesn't).

    The trick: Remove all divisions from the intermediate results and only divide once at the end. This is done by keeping track of all the (partial) numerators and denominators. If the discriminant should be 0 then it's numerator will be 0. No round-off error here as long as values at intermediate additions are within a magnitude of ~2^45 from each other (which is usually the case).

    // Calculate p and q.
    double pn = 3 * a * c - b * b;
    double pd = 3 * a * a;
    
    double qn1 = 2 * b * b * b;
    double qd1 = 27 * a * a * a;
    double qn2 = b * c;
    double qn3 = qn1 * pd - qn2 * qd1;
    double qd3 = qd1 * pd;
    double qn = qn3 * a + d * qd3;
    double qd = qd3 * a;
    
    // Calculate the discriminant.
    double dn1 = qn * qn;
    double dd1 = 4 * qd * qd;
    double dn2 = pn * pn * pn;
    double dd2 = 27 * pd * pd * pd;
    
    double dn = dn1 * dd2 + dn2 * dd1;
    double dd = dd1 * dd2;
    discriminant = dn / dd;
    

    (only checked on the provided input values, so tell me if something's wrong)

提交回复
热议问题