-2

I've been doing Asabeneh 30 day JavaScript roadmap and in day 7, level 2, there is an exercise that asks us to build a quadratic function solver. I've tried my function with a couple of numbers and seems to work out just fine, but when plugging in some other numbers (for instance, periodic numbers as roots) the function just outputs two random values

Example:

function solveQuadEquation (a = 0, b = 0, c = 0) { 
    let x1 = ((-1 * b + Math.sqrt(b * b - 4 * a * c)) / 2 * a)

    let x2 = ((-1 * b - Math.sqrt(b * b - 4 * a * c)) / 2 * a)

    let discriminant = Math.pow(b, 2) - 4 * a * c

    if (discriminant > 0) {
        return 'The function has two solutions: ' + x1 + ' , ' + x2
    } else if (discriminant === 0) {
        return 'The function has two repeated roots: ' + x1
    } else {
        return 'the function has no real values'
    }

    return [x1, x2];
}

console.log(solveQuadEquation(9, 3, -4))

The console outputs

// The function has two real values: 42.161192594... , -69.161192594...

any ideas on what might be wrong with it?

thanks!!

str8cho
  • 11
  • 1
    _"outputs two random values"_... there's nothing random here. It outputs the results of your calculations – Phil Aug 11 '22 at 23:20
  • 1
    JavaScript doesn't have built-in complex numbers, so `Math.sqrt()` will not work if `b * b - 4 * a * c` is negative. See https://stackoverflow.com/questions/15399340/how-to-calculate-with-imaginary-numbers-in-javascript – Barmar Aug 11 '22 at 23:21
  • If you only care about real roots, just check if `b * b - 4 * a * c` is negative. If it is, report that there are no real roots. – Barmar Aug 11 '22 at 23:22

1 Answers1

1

The quadratic formula is (-b +/- sqrt(delta))/2a
Your code does a*(-b +/- sqrt(delta))/2
Watch your brackets next time.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Oreoezi
  • 129
  • 9