Maroof G - 2 months ago 13x

Python Question

I am trying to run a quadratic equation in python. However, it keeps on giving me an error "RuntimeWarning: invalid value encountered in sqrt".

Here's my code:

`import numpy as np`

a = 0.75 + (1.25 - 0.75)*np.random.randn(10000)

print a

b = 8 + (12 - 8)*np.random.randn(10000)

print b

c = -12 + 2*np.random.randn(10000)

print c

x0 = (-b - np.sqrt(b**2 - (4*a*c)))/(2 * a)

print x0

Your expert suggestion will be extremely helpful. Thanks in advance

Answer

This is not 100% Python related. You can't calculate the square root of a negative number (when dealing with real numbers that is).

You didn't take any precautions for when `b**2 - (4*a*c)`

is a negative number.

```
>>> import numpy as np
>>>
>>> np.sqrt(4)
2.0
>>> np.sqrt(-4)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan
```

Let's test if you have negative values:

```
>>> import numpy as np
>>>
>>> a = 0.75 + (1.25 - 0.75) * np.random.randn(10000)
>>> b = 8 + (12 - 8) * np.random.randn(10000)
>>> c = -12 + 2 * np.random.randn(10000)
>>>
>>> z = b ** 2 - (4 * a * c)
>>> print len([_ for _ in z if _ < 0])
71
```

Source (Stackoverflow)

Comments