如果您不介意使用外部SMT求解器,可以使用SBV包:
Prelude Data.SBV> allSat $ \x -> 2*x^3-19*x^2+15*x+72 .== (0::SReal)
Solution #1:
s0 = 3.0 :: Real
Solution #2:
s0 = 8.0 :: Real
Solution #3:
s0 = -1.5 :: Real
Found 3 different solutions.
您可以放心,根将是精确的,即不会发生舍入误差。 Real
类型对应于无限精确的代数实数。如果结果不能以有限的形式打印,则将其写为简单方程的根,并扩展到当前打印精度:
Prelude Data.SBV> allSat $ \x -> x^2-2 .== (0::SReal)
Solution #1:
s0 = root(1, x^2 = 2) = -1.414213562373095... :: Real
Solution #2:
s0 = root(2, x^2 = 2) = 1.414213562373095... :: Real
Found 2 different solutions.
Prelude Data.SBV> allSatWith z3{printRealPrec=20} $ \x -> x^2-2 .== (0::SReal)
Solution #1:
s0 = root(1, x^2 = 2) = -1.4142135623730950488... :: Real
Solution #2:
s0 = root(2, x^2 = 2) = 1.4142135623730950488... :: Real
Found 2 different solutions.
Prelude Data.SBV> allSat $ \x -> x^2+1 .== (0::SReal)
No solutions found.
如果仅有一些根是实数,那么它们将被找到:
Prelude Data.SBV> allSat $ \x -> x^3+2*x-1 .== (0::SReal)
Solution #1:
s0 = root(1, x^3+2x = 1) = 0.4533976515164037... :: Real
This is the only solution.
PS. 为了使所有的工作正常运行,请不要忘记首先在您的计算机上安装Z3。 您可以从 https://github.com/Z3Prover/z3/releases 获取最新版本。
dsp
包中的Polynomial.Roots
模块。该模块处理复值(复系数和复根)。1+2x+2x²=0
:Prelude> import Polynomial.Roots
Prelude Polynomial.Roots> roots 1e-16 1000 [1,2,2]
[(-0.5) :+ (-0.5),(-0.5) :+ 0.5]
作为一个合理性检查,R给出了相同的结果:
> polyroot(c(1,2,2))
[1] -0.5+0.5i -0.5-0.5i
separateRoots
应该可以帮助你完成大部分工作,但它似乎不能正确地工作。例如,separateRoots BE [1,0,-1]
无法分离。 - luqui