且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

该函数解三次方程式有什么问题?

更新时间:1970-01-01 07:57:06

Wolfram Alpha confirms that the roots to your last cubic are indeed

(-4, -2, 2)

而不是您所说的

...它应该返回[4.0, -4.0, -2.0]

尽管我猜错了,但您的程序却给出了

Not withstanding that (I presume) typo, your program gives

[(-4+1.4802973661668753e-16j), (2+2.9605947323337506e-16j), (-2.0000000000000004-1.1842378929335002e-15j)]

完全相同的根源10**(-15)的正确解决方案.正如其他人所说,微小假想部分可能是由于四舍五入.

Which to accuracy of 10**(-15) are the exact same roots as the correct solution. The tiny imaginary part is probably due, as others have said, to rounding.

请注意,如果您使用的是 Cardano的解决方案,则必须始终使用精确算术来始终正确取消. .这就是为什么像MAPLEMathematica这样的程序存在的原因之一,通常是从公式到实现之间存在脱节.

Note that you'll have to use exact arithmetic to always correctly cancel if you are using a solution like Cardano's. This one of the reasons why programs like MAPLE or Mathematica exist, there is often a disconnect from the formula to the implementation.

要仅获取纯python中数字的实部,请调用.real.示例:

To get only the real portion of a number in pure python you call .real. Example:

a = 3.0+4.0j
print a.real
>> 3.0