4
print("input a, b and c for a quadratic equation ax^2+bx+c=0")
a = float(input("a ="))
b = float(input("b ="))
c = float(input("c ="))


D = (b**2) - (4*a*c)

if D>0: 
 s1 = (-b+D**0.5)/(2*a)
 s2 = (-b-D**0.5)/(2*a)
 print("the two solutions are: {} and {}".format(s1,s2))

elif D==0:
 s3 = (-b)/(2*a)
 print("the one solution is: {}".format(s3)) 

elif D<0:
 print("no solution")

This code works, but I need to make this code into a function that will only print c if the difference between a and c is within a tolerance "tol", no idea how to proceed.

Kelouis
  • 55
  • 1
  • 6

1 Answers1

0

You could use either Python's inbuilt abs function or NumPy's isclose function.

You could add another if statement with the condition as abs(a - c) < tol or np.isclose(a, c), while specifying the atol (absolute tolerance) or rtol (relative tolerance) optional parameters to the desired value.

Refer: https://numpy.org/doc/stable/reference/generated/numpy.isclose.html

Nikhil Kumar
  • 1,015
  • 1
  • 9
  • 14