Hacker News new | past | comments | ask | show | jobs | submit login

From the book "real computing made real" by Acton, the suggestion is to first view (not always!) the quadratic as x^2 + 2bx + c, so its roots are -b +/- sqrt(b^2 - c). The product of the roots is c and therefore we can compute the root that does not do the subtraction and then divide c by that root to get the other root.

This avoids any of the bad subtraction.

Some sample js code that corresponds to quadratic in the post:

    b = 5e7
    c = 1

    d = b*b - c

    if (d >= 0) {
        m = Math.sqrt(d)   
        if ( b> 0) {
            r = -b - m
            s = c/r
        } else if ( b <  0) {
            s = -b + m
            r = c/s
        } else {
            r = m
            s = -r
        }
        console.log(r, s)
    } else {
        console.log("no real roots");
    }
This gives the correct roots for this problem in one go.



Numerical Recipes says to find q=-1/2[b+sgn(b)sqrt(b^2-4ac)] and then find x1=q/a and x2=c/q - is that better?

http://www.solipsys.co.uk/cgi-bin/sews.py?NumericallyStableS...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: