[Tutor] Math: integers to a fractional power
Dave Angel
davea at ieee.org
Tue Nov 16 02:11:42 CET 2010
On 2:59 PM, Matthew Denaburg wrote:
> Hi,
>
> OK, so I have a question for you math people: I am trying to solve a quartic equation (Ax^4 + Bx^3 + Cx^2 + Dx + E) using Ferrari's Method, which I found on Wikipedia at this location.
>
> I'm using Python 3.1.2 (on Mac OS X 10.6, in case that matters).
>
> First, since I don't know Python very well, I was wondering if there is an easier way to do this, without having to install any modules. (I can't figure out how to put anything on my PYTHONPATH).
>
> If not there is not an easier way without installing a module, could someone recommend a module AND give me a link to detailed instructions for how to install it?
>
> I would PERFER to continue using Ferrari's Method, but am not opposed to trying something else.
>
> My only problem when using Ferrari's Method was this error:
>
> Traceback (most recent call last):
> File "Problem309.py", line 135, in<module>
> print(main())
> File "Problem309.py", line 127, in main
> math.pow(L1, 2)-math.pow(L2, 2))
> File "Problem309.py", line 73, in sQuartic
> W = math.pow(alpha + 2 * y, 1/2)
> TypeError: can't convert complex to float
>
> Now, your first thought is probably that I have a negative number in the square root, or that I should be using math.sqrt. According to this method, I need to use cube roots as well, and I wanted to keep my code consistent. I also have checked, and the only variable that could be ending up as a complex number is the variable y. So, here is
You don't have to guess. Once you come to that conclusion, check it.
Put a print( y), or perhaps print (repr(y)) and check the value.
> <snip>
>
> The problem I am having is that, as far as I can tell, is that U is turning into a complex number, which is impossible! You can take the cube root of any number, positive or negative!
<snip>
I don't know in particular, but if you were to raise a negative number
to the .3333 power, the answer would be complex. Perhaps you're getting
hit with some roundoff/quantization error. 1/3 cannot be exactlly
represented, of course. I'd be curious if that's the situation here.
If so, you could finesse the problem with the expression:
sign * (abs(x) ** (1.0/3))
where sign is +1 or -1 representing the sign of x.
DaveA
More information about the Tutor
mailing list