Tho*_*mas 2 math haskell pattern-matching complex-numbers
所以我已经在haskell中创建了自己的复数数据类型.
由于这里的另一个问题,我也得到了一个能解决二次方程的函数.
现在唯一的问题是,在尝试解决具有复杂根的二次方时,代码会在拥抱中生成解析错误.
即拥抱......
Main> solve (Q 1 2 1)
(-1.0,-1.0)
Main> solve (Q 1 2 0)
(0.0,-2.0)
Main> solve (Q 1 2 2)
(
Program error: pattern match failure: v1618_v1655 (C -1.#IND -1.#IND)
Run Code Online (Sandbox Code Playgroud)
在应用平方根之后,它看起来像我的问题,但我真的不确定.任何试图找出问题的帮助或任何关于这个错误意味着什么的指示都将是辉煌的.
谢谢,
托马斯
代码:
-- A complex number z = (re +im.i) is represented as a pair of Floats
data Complex = C {
re :: Float,
im :: Float
} deriving Eq
-- Display complex numbers in the normal way
instance Show Complex where
show (C r i)
| i == 0 = show r
| r == 0 = show i++"i"
| r < 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r < 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| r > 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r > 0 && i > 0 = show r ++ " + "++ show (C 0 i)
-- Define algebraic operations on complex numbers
instance Num Complex where
fromInteger n = C (fromInteger n) 0 -- tech reasons
(C a b) + (C x y) = C (a+x) (b+y)
(C a b) * (C x y) = C (a*x - b*y) (b*x + b*y)
negate (C a b) = C (-a) (-b)
instance Fractional Complex where
fromRational r = C (fromRational r) 0 -- tech reasons
recip (C a b) = C (a/((a^2)+(b^2))) (b/((a^2)+(b^2)))
root :: Complex -> Complex
root (C x y)
| y == 0 && x == 0 = C 0 0
| y == 0 && x > 0 = C (sqrt ( ( x + sqrt ( (x^2) + 0 ) ) / 2 ) ) 0
| otherwise = C (sqrt ( ( x + sqrt ( (x^2) + (y^2) ) ) / 2 ) ) ((y/(2*(sqrt ( ( x + sqrt ( (x^2) + (y^2) ) ) / 2 ) ) ) ) )
-- quadratic polynomial : a.x^2 + b.x + c
data Quad = Q {
aCoeff, bCoeff, cCoeff :: Complex
} deriving Eq
instance Show Quad where
show (Q a b c) = show a ++ "x^2 + " ++ show b ++ "x + " ++ show c
solve :: Quad -> (Complex, Complex)
solve (Q a b c) = ( sol (+), sol (-) )
where sol op = (op (negate b) $ root $ b*b - 4*a*c) / (2 * a)
Run Code Online (Sandbox Code Playgroud)
您的错误中的数字似乎是非规范化的:
Run Code Online (Sandbox Code Playgroud)
(C -1.#IND -1.#IND)
在这种情况下,您不能假设浮动的任何比较都有效.这是浮点数的定义.然后你的定义显示
show (C r i)
| i == 0 = show r
| r == 0 = show i++"i"
| r < 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r < 0 && i > 0 = show r ++ " + "++ show (C 0 i)
| r > 0 && i < 0 = show r ++ " - "++ show (C 0 (i*(-1)))
| r > 0 && i > 0 = show r ++ " + "++ show (C 0 i)
Run Code Online (Sandbox Code Playgroud)
由于非规范化数字,给模式失败留下了机会.您可以添加以下条件
| otherwise = show r ++ "i" ++ show i"
Run Code Online (Sandbox Code Playgroud)
现在为什么会这样,当你评价时
b * b - 4 * a * c
Run Code Online (Sandbox Code Playgroud)
使用Q 1 2 2,你获得-4,然后在root中,你落入你的最后一个案例,并在第二个等式中:
y
-----------------------------
________________
/ _______
/ / 2 2
/ x + \/ x + y
2 * \ / ----------------
\/ 2
Run Code Online (Sandbox Code Playgroud)
-4 + sqrt( (-4) ^2) == 0从那里,你注定要失败,除以0,接着是"NaN"(不是数字),搞砸其他一切