I have a question, the output to my function here gives (NaN, NaN). Did I miss something in the code or?
roots :: (Float, Float, Float) -> (Float, Float)
roots (a,b,c) =
let s = sqrt (b*b - 4.0*a*c)
d = 2.0*a
in ((-b s)/d, (-b - s)/d)
I searched up and found that NaN is not a number, but why is it displaying when I execute my quadratic equation code in Haskell? Thanks.
CodePudding user response:
Since the roots can be complex, they can't be represented in a Float
in all cases. A possible fix is to switch the result type to involve Complex Float
, which stores both the real and imaginary part.
Below, x : y
stands for a complex number with real part x
and imaginary part y
.
import Data.Complex
roots :: (Float, Float, Float)
-> (Complex Float, Complex Float)
roots (a,b,c) =
let s = sqrt ((b*b - 4.0*a*c) : 0)
d = 2.0*a : 0
b' = b : 0
in ((-b' s)/d, (-b' - s)/d)
Now, complex roots are printed instead of NaN
s.
> roots (1,0,1)
(0.0 : 1.0,(-0.0) : (-1.0))
(Note that if a
is zero we can still get a NaN
if we try to compute 0/0
. But that's a distinct issue.)
By the way, in Haskell we usually define functions in their curried form, i.e.
roots :: Float -> Float -> Float
-> (Complex Float, Complex Float)
roots a b c = ...
CodePudding user response:
In order to determine why your code is returning (NaN, NaN)
, we would need to see the input that you are providing to the function, as well as any error messages that you may be getting.
One possible reason for your code returning (NaN, NaN)
is that the value of the b
squared minus 4 times a
times c
is negative, which would cause the square root in the code to return a complex number (i.e. a number with both a real and imaginary part) rather than a real number. In Haskell, complex numbers are not supported by the Float
type, so attempting to take the square root of a negative number would result in the NaN
(not a number) value being returned.
Another possible reason for your code returning (NaN, NaN)
is that the value of a
is 0. In this case, the code would be dividing by 0, which is undefined and would result in NaN
being returned.
It is also possible that there is a mistake in the code that is causing it to return (NaN, NaN)
even when the input is valid. Without more information, it is difficult to say for sure what the problem might be.