![]() |
Quadratic Formula in Python
I have written a python code for quadratic formula :) . However, I need both real and complex numbers for my results. I have done research and noticed two differences: real numbers uses import math and complex numbers uses import cmath
Here's my code. I would like to know what I have done wrong. I have even put my comments on there: :
# quadraticcomplex.py |
Re: Quadratic Formula in Python
Don't use cmath. Use math.
Sorry about that. Edit: Just force it to be positive before you square root it, and then indicate that it's an imaginary number, calculating the real and imaginary portion how you normally would by hand. :
disc = b**2 - 4*a*c # discriminantSo it's basically done how someone solving it with a pencil would do it. That's usually an ideal way of thinking about how to program a solution. By the way, wrap your code in [code][/code] tags next time. |
Re: Quadratic Formula in Python
Is this the same for real numbers too?
|
Re: Quadratic Formula in Python
[Delete]
|
Re: Quadratic Formula in Python
Sorry about that. I forgot that imaginary numbers are calculated in pieces when you use the quadratic formula. It's been too long.
My first post is now edited. |
Re: Quadratic Formula in Python
Oh Thank you! Yes I am new to programming in python. I thought that the code was straight. But when I have noticed on import math, it would calculate the real numbers of the quadratic formula. I also thought that cmath would calculate complex numbers for quadratic formula. I thought in python, j represented complex numbers.
|
Re: Quadratic Formula in Python
So is this the correct format for the code?
:
def main(): # beginning of the code |
Re: Quadratic Formula in Python
Yes, that should work, if you fix your indenting. And print out the output in a way the user can understand.
If you want it to be able to handle both real and imaginary roots, you'll basically need to split the program up into two parts. If the discriminant is less than 0, you use the end part of the code I gave you. Otherwise, you make it use the end part of your original code. If you understand enough about your code, and the code in my edited post, it should be enough to piece together a complete solution. And you could use the cmath library for complex numbers, but it's intended for doing calculations on known complex numbers. Such as taking the cosine of an imaginary number. It's not good for what you're trying to do here. |
Re: Quadratic Formula in Python
I am going to try it out and then let you know if it works. Hopefully it will! Let me go check! Thanks Sane. But let me go check really quick.
|
Re: Quadratic Formula in Python
I tried running the program and it doesn't display my results at all. Also, when I tried performing calculations, the program would not run.
|
| All times are GMT -5. The time now is 3:36 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC