What's wrong with this function to solve cubic equations?

后端 未结 3 1011
死守一世寂寞
死守一世寂寞 2021-01-14 10:56

I am using Python 2 and the fairly simple method given in Wikipedia\'s article \"Cubic function\". This could also be a problem with the cube root function I have to define

3条回答
  •  余生分开走
    2021-01-14 11:40

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

    (-4, -2, 2)
    

    and not as you say

    ... it should return [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)]
    

    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.

    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.

    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
    

提交回复
热议问题