4

I am making a function on python3 that solves ax^2+bx+c so a quadratic equation

My code looks like this:

def quadratic(a, b, c):
    return a*x**2 + b*x + c

But it wont let me do this because x is undefined. I want to take the argument x on a test code that looks like this:

def testQuadratic(a, b, c, x):
    try:
        return quadratic(a, b, c)(x)
    except TypeError:
        return None

Can anyone tell me how I can fix this? Thank you!!

Georgy
  • 12,464
  • 7
  • 65
  • 73
WinnyDaPoo
  • 145
  • 7

4 Answers4

7

You can make use of the fact that Python supports first-class functions, that can be passed into and returned from other functions.

def make_quadratic(a, b, c):
    def f(x):
        return a*(x**2) + b*x + c
    return f

# You would call the returned function
my_quadratic = make_quadratic(a, b, c)

# You can then call my_quadratic(x) as you would elsewhere
jrmylow
  • 679
  • 2
  • 15
3

Your quadratic function should... return a function!

def quadratic(a, b, c):
  def calculate_quadratic(x):
    return a*x**2 + b*x + c
  return calculate_quadratic
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

It's unclear whether you intend 'solve' to mean

  1. find a root of the quadratic equation, or
  2. produce an output for a given value of x

Since you're taking x as an input argument, I'll assume the second option (snatchysquid gave an answer for the first option):

def quadratic(a, b, c):
    return a*x**2 + b*x + c

def testQuadratic(a, b, c, x):
    try:
        return quadratic(a, b, c, x)
    except TypeError:
        return None

of course unless you need def quadratic for some other reason, then it would be simpler to use:

def testQuadratic(a, b, c, x):
    try:
        return a*x**2 + b*x + c
    except TypeError:
        return None

You still might want to handle other errors besides TypeError.

David Collins
  • 848
  • 3
  • 10
  • 28
0

You can read about quadratic equations here and in wikipedia.

There is a formula for solving quadratic equations so you can use this code:

import math

def quadratic_equation(a, b, c):
    """
    :params a,b,c: the coefficients of the equation ax^2+bx+c=0
    :return: a tuple (of len 2) with the solutions to the equation
    :rtype: tuple
    """

    discriminant = b ** 2 - (4 * a * c)
    if discriminant < 0:
        return None, None
    if discriminant == 0:
        return -b / (2 * a), None
    return (-b + math.sqrt(discriminant)) / (2 * a), (-b - math.sqrt(discriminant)) / (2 * a)

The reason your code doesn't work is that python does not understand "missing variables", and thinks that x is some defined variable, for example x = 2, but you use the math notation which python does not understand.

snatchysquid
  • 1,283
  • 9
  • 24