我需要编写一个程序来解决二次方程,并返回复数结果。
我已经定义了一个复数,并将其声明为num的一部分,因此可以进行加、减和乘法。
我还为二次方程定义了一个数据类型,但是现在我卡在了实际解决二次方程上。我的数学很差,所以任何帮助都将不胜感激...
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) = STUCK!
编辑:我好像错过了使用自己的复数数据类型所学习的关于自定义数据类型的整个重点。我很清楚我可以使用 complex.data。非常感谢能够利用 我的 解决方案给予任何帮助。
编辑 2: 我的初始问题似乎措辞不当。我知道二次公式会返回一个或两个根。我遇到困难的地方是,如何使用上述代码将这些根作为 (complex, complex) 元组返回。
我很清楚我可以使用下面展示的内置二次函数,但这并不是练习的目的。练习的目的,以及创建自己的复数数据类型,是为了学习自定义数据类型。
Data.Complex
中的Complex
。 - yairchu