← RU Pythoncursus

Uitwerking: ABC-formule

from math import sqrt

a = 3
b = 3
c = -5

D = b*b - 4*a*c
x0 = (-b - sqrt(D)) / (2*a)
x1 = (-b + sqrt(D)) / (2*a)

print(x0, x1)


# Uitgebreide uitwerking


def abc(a, b, c):
    D = b*b - 4*a*c
    x0 = (-b - sqrt(D)) / (2*a)
    x1 = (-b + sqrt(D)) / (2*a)
    return (x0, x1)

print(abc(3, 3, -5))


# uitwerking met relevante polynomen


a,b,c = 1, 7, -18

D = b*b - 4*a*c
x0 = (-b - sqrt(D)) / (2*a)
x1 = (-b + sqrt(D)) / (2*a)

print(x0, x1)

a,b,c = 1, 6.28318, -9.86959

D = b*b - 4*a*c
x0 = (-b - sqrt(D)) / (2*a)
x1 = (-b + sqrt(D)) / (2*a)

print(x0, x1)

a,b,c = 3, -12, 0

D = b*b - 4*a*c
x0 = (-b - sqrt(D)) / (2*a)
x1 = (-b + sqrt(D)) / (2*a)

print(x0, x1)

a,b,c = 2, -37, 1

D = b*b - 4*a*c
x0 = (-b - sqrt(D)) / (2*a)
x1 = (-b + sqrt(D)) / (2*a)

print(x0, x1)

# Uitgebreide uitwerking


def quadform(a, b, c):
  return [(-b + s * sqrt(b*b - 4*a*c)) / (2*a) for s in (-1, 1)]

trials = [(1, 7, -18),
          (1, 6.28318, -9.86959),
          (3, -12, 0),
          (2, -37, 1)
         ]

for trial in trials:
  print(quadform(*trial))

# de vergelijking x**2 + 5*x + 7 = 0 gaat natuurlijk fout, want:
a, b, c = 1, 5, 7
D = b*b - 4*a*c
print('D < 0:', D < 0)