Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Help making quadratic formula in python

Help making quadratic formula in python

I am trying to make a program in which you enter the A, B, and C variables in the quadratic formula and it find's X's two values. I already set up an if-else statement so that if the discriminant is negative, it will tell the user there are no solutions, however I am having trouble on the actual math part.

The quadratic formula is x = -b±√b^2-4ac all divided by 2a.

Part of my code is below. As you can see in the else statement, I set up two variables because X can have two different answers because there is the plus-minus sign. Would the way I did it be the correct way to do it? When I try to test it out, it gives the wrong answers so my math is wrong somehow.

Code:
#Makes a variable for the discriminant
disc = b2 - 4*a*c

#If the discriminant is less than 0, it says no real solutions
if disc < 0:
print "No real solutions"

#If the discriminant is 0, it finds the 1 value of X
elif disc == 0:
x = -b+((b
2 - 4*a*c)**.5)/2*a
print "x = " + str(x)
PHP Code

<?php 
import math
def quadratic
(a, b, c):
    
xs = [0,0]
    
xs[0] = (-b - math.sqrt(b**2 - 4*(a*c)))/(a*2)
    
xs[1] = (-b + math.sqrt(b**2 - 4*(a*c)))/(a*2)
    return 
xs 
(Jul 13, 2017 04:12 AM)Davian Wrote:  
PHP Code

<?php 
import math
def quadratic
(a, b, c):
    
xs = [0,0]
    
xs[0] = (-b - math.sqrt(b**2 - 4*(a*c)))/(a*2)
    
xs[1] = (-b + math.sqrt(b**2 - 4*(a*c)))/(a*2)
    return 
xs 

This is the best way to do it. You could also use cmath instead if you wanted to be able to handle complex numbers.
You may want to use cmath here, not the math module, because of course the quadratic formula can have imaginary numbers. Adding an "imaginary" boolean parameter would be one solution here.

PHP Code

<?php 
from __future__ import print_function
import cmath
import math
import operator

def quadratic
(a, b, c, imaginary=True):
    
sqrt = cmath.sqrt if imaginary else math.sqrt
    def _quad
(op):
        try:
            return 
op(-b, sqrt(b**2 - 4*a*c))/(2*a)
        
except ValueError:
            return 
None
    
return _quad(operator.add), _quad(operator.sub)

# define a, b, c
x, y = quadratic(a, b, c) # or quadratic(a, b, c, False) for real values only
print(x, y) 
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by Bass_ReevesAug 20, 2023 01:44 AM 9 632 Aug 20, 2023 01:44 AM
Last Post: Lucky4L
[Python] by GerymcJul 3, 2017 09:08 AM 5 199 Jul 3, 2017 09:08 AM
Last Post: arkoydas
[Shell] by jahwiAug 20, 2016 03:15 PM 3 196 Aug 20, 2016 03:15 PM
Last Post: gogglebot