First of all; english is not my main language so bare in mind. (The text in the script is in norwegian, I will try to translate as well as possible)
I am trying to create a python script that solves a second degree equation or a quadratic? equation I think. If i understand it correctly I should use cmath module to be able to solve complex roots, however, I havent got that far in my class yet and it is my task to only use math module and return a answer that looks something like this (if the roots are complex): "There is no real solution".
Also, when using normal math module I get returned a "math domain error" when trying to for example put a = 6, b = 11 and c = 32.
Thank you in advance.
Edward
Trying to use a if/elif/else thingy, have tried cmath (it returns a waaaay to long and unreadable answer)
My code is here under this (hopefully I have pasted it correctly, sorry in advance:
#Importerer math
import math
print("Programmet skal løse andregradslikningen ")
print("ax^2 bx c = 0 ved hjelp av abc-formelen")
print("Skriv inn verdiene for a, b og c.")
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
d = (b**2) - (4*a*c)
sol1 = (-b math.sqrt(d))/(2*a)
sol2 = (-b-math.sqrt(d))/(2*a)
if d < 0:
print("Likningen har ingen løsning")
elif d==0:
print(f"Løsning x = {-b/(2*a)}")
else:
print("Løsningen er")
print(f"x = {sol1}, og x= {sol2}")
CodePudding user response:
You have to check if d
is negative before you try to call math.sqrt(d)
, so you don't get an error.
d = (b**2) - (4*a*c)
if d < 0:
print("Likningen har ingen løsning")
elif d==0:
print(f"Løsning x = {-b/(2*a)}")
else:
sol1 = (-b math.sqrt(d))/(2*a)
sol2 = (-b-math.sqrt(d))/(2*a)
print("Løsningen er")
print(f"x = {sol1}, og x= {sol2}")