Question: Quadratic Formula Assignment Producing -nan

Hi everyone. I’m trying to complete the Quadratic Formula assignment but my print statements are producing the wrong output.

Instead of producing a number I get -nan.

Here’s my code and a screenshot:

var a: Double = 2.0
var b: Double = 5.0
var c: Double = 3.0

var root1: Double = 0
root1 = (b * 2) - 4 * (a * c)
var root2: Double = (b * 2) - 4 * (a * c)

//no -nan
print(root1)

// produces -nan
root1 = root1.squareRoot()
root2 = root2.squareRoot()

// troubleshooting
print(root1)


root1 = -b + root1
root1 = root1 / (2 * a)

root2 =  -b - root2
root2 = root2 / (2 * a)

print(root1)
print(root2)

The quadratic formula is:       scrn1

In the discriminant (the expression underneath the square root),    b has an exponent of 2.

Exponentiation means:

scrn3

In your screenshot, you have interpreted exponentiation of b to the power 2 as multiplication by 2,

// You wrote:
(b * 2) - 4 * (a * c)

// It should be:
(b * b) - 4 * (a * c)

Alternatively, you could use the pow function (whose first argument is the base and the second argument is the exponent),

import Foundation
 
(pow(b, 2)) - 4 * (a * c)
2 Likes

Thank you so much. Obviously, my math skills are not too strong.