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

后端 未结 3 997
死守一世寂寞
死守一世寂寞 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:22

    You are using integer values - which are not automatically converted to floats by Python. The more generic solution will be to write coefficients in the function as float numbers - 18.0 instead of 18, etc. That will do the trick An illustration - from the code:

    >>> 2**(1/3)
    1
    >>> 2**(1/3.)
    1.2599210498948732
    >>> 
    
    0 讨论(0)
  • 2021-01-14 11:29

    Hooked's answer is the way to go if you want to do this numerically. You can also do it symbolically using sympy:

    >>> from sympy import roots
    >>> roots('2*x**3 + 8*x**2 - 8*x - 32')
    {2: 1, -4: 1, -2: 1} 
    

    This gives you the roots and their multiplicity.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题